-
python中set()函数的用法_Python Pandas dataframe.set_value()用法及代码示例
2020-12-03 23:55:14Python是进行数据分析...Pandas dataframe.set_value()函数将单个值放在传递的列和索引处。它以轴标签为输入,并以标量值放置在 DataFrame 中的指定索引处。替代此功能的是.at[]或者.iat[]。用法:DataFrame.set_va...Python是进行数据分析的一种出色语言,主要是因为以数据为中心的python软件包具有奇妙的生态系统。 Pandas是其中的一种,使导入和分析数据更加容易。
Pandas dataframe.set_value()函数将单个值放在传递的列和索引处。它以轴标签为输入,并以标量值放置在 DataFrame 中的指定索引处。替代此功能的是.at[]或者.iat[]。
用法:DataFrame.set_value(index, col, value, takeable=False)
参数:
index: row label
col: column label
value: scalar value
takeable: interpret the index/col as indexers, default False
返回:frame:DataFrame如果包含标签对,将引用调用DataFrame,否则将引用一个新对象
范例1:采用set_value()函数将数据帧中的值设置为特定索引。
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":[1, 5, 3, 4, 2],
"B":[3, 2, 4, 3, 4],
"C":[2, 2, 7, 3, 4],
"D":[4, 3, 6, 12, 7]})
# Print the dataframe
df
让我们使用dataframe.set_value()用于设置特定索引值的函数。
# set value of a cell which has index label "2" and column label "B"
df.set_value(2, 'B', 100)
输出:
范例2:采用set_value()用于设置 DataFrame 中不存在的索引和列的值的函数。
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":[1, 5, 3, 4, 2],
"B":[3, 2, 4, 3, 4],
"C":[2, 2, 7, 3, 4],
"D":[4, 3, 6, 12, 7]})
# Print the dataframe
df
让我们使用dataframe.set_value()用于设置特定索引值的函数。
# set value of a cell which has index label "8" and column label "8"
df.set_value(8, 8, 1000)
输出:
请注意,对于 DataFrame 中不存在的行和列,已插入新的行和列。
-
python center函数的用法_python 怎么查看函数的用法
2021-01-28 15:42:051、help()help()函数可以比较详细的介绍一个函数的使用方法。如:>>>help(print)Helponbuilt-infunctionprintinmodulebuiltins:print(...)print(value,...,sep='',end='',file=sys.stdout,flush=False)...1、help()
help()函数可以比较详细的介绍一个函数的使用方法。
如:>>>help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='
', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
相关推荐:《Python入门教程》
2、dir()
dir()函数可以列出所查询内容的内置属性和方法。
如:>>>dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize',
'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum',
'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex',
'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
dir()也可以查询python的内置方法。>>>dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError',
'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError',
'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit',
'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError',
'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None',
'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning',
'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError',
'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit',
'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError',
'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__',
'__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes',
'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals',
'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit',
'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
'tuple', 'type', 'vars', 'zip']
3、xx.__doc__
查看使用帮助,一般为创建该类时候的备注。
4、xx.__dict__
查看对象所拥有的属性。
5、在IDLE中点击help中的python docs
在输入栏中打上你要查找的内容直接搜索,不过这里应该只有python自带的一下基本的模块。
-
python remove函数用法_python中remove函数的踩坑记录
2021-01-12 05:48:02对于python中的remove()函数,官方文档的解释是:Remove first occurrence of value.大意也就是移除列表中等于指定值的第一个匹配的元素。语法list.remove()参数obj 参数:从列表中删除的对象的索引返回值删除后不会...摘要:
在python的使用过程中,难免会遇到要移除列表中对象的要求。这时可以使用remove函数。
对于python中的remove()函数,官方文档的解释是:Remove first occurrence of value.大意也就是移除列表中等于指定值的第一个匹配的元素。
语法
list.remove()
参数
obj 参数:从列表中删除的对象的索引
返回值
删除后不会返回值
常见用法:
a = [1,2,3,4],a.remove(1),然后a就是[2,3,4];对于a = [1,1,1,2],其结果也是[1,1,2],这是最基本的用法。
但是对于下面这个:
a = [1,2,3,4]
for i in a:
a.remove(i)
# 结果
a = [2,4]
或者说
a = [1,1,1,1,1,2]
for i in a:
a.remove(1)
#结果
a = [1,1,2]
是不是跟想象中的不一样,其主要原因如下(^表示当前迭代器位于列表中的位置):
a = [ 1 , 2 , 3 , 4]
假设此时 ^
默认情况下只想第一个元素,然后执行a.remove(1),然后下标向后移动,列表因为删除了元素,后面的向前移动,如下:
a = [ 2 , 3 , 4]
此时 ^
此时执行a.remove(3),重复上面的移动
a = [ 2 , 4]
此时 ^
因为已经到了列表的边界,故结束遍历,并返回`a = [2,4]`。
解决办法:
# 一下为解决办法之一
d = dict(zip(range(len(a)), a))
[v for k, v in d.items() if v != value]
总结:
关于python列表的remove操作涉及了列表下标的移动以及列表中元素的移动,涉及了一些关于数组的知识。其核心问题就是前面所说的。
到此这篇关于python中remove函数的踩坑记录的文章就介绍到这了,更多相关python中remove函数坑内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
-
python常用函数的用法_python中字典常用的函数和用法
2020-11-24 00:14:52字典的特性:key-value结构key必须可hash、且必须为不可变数据类型、必须唯一可存放任意多个值、可修改、可以不唯一无序查找速度快dict_fruit = {'apple':'苹果','banana':'香蕉','cherry':'樱桃','avocado':'牛油果...字典的特性:
key-value结构
key必须可hash、且必须为不可变数据类型、必须唯一
可存放任意多个值、可修改、可以不唯一
无序
查找速度快
dict_fruit = {'apple':'苹果','banana':'香蕉','cherry':'樱桃','avocado':'牛油果','watermelon':'西瓜'}
"apple" in dict_fruit >>> True # 判断是否在字典中
for key in dict_fruit: >>> apple,banana,cherry,avocado,watermelon # 遍历字典中的key (默认遍历与 for key in res.keys(): 相同) 【通过这查找values的值】
for value in res.values(): >>> 苹果,香蕉,樱桃,牛油果,西瓜 #遍历字典中的value
for key,value in dict_fruit.items(): >>> apple 苹果、banana 香蕉、cherry 樱桃、avocado 牛油果、watermelon 西瓜 #遍历字典中的 key和 values 【基本不用】
增加:
dict_fruit["pineapple"] = “菠萝”
删除:
dict_fruit.pop["apple"] #删除同时返回删除的值
dict_fruit.popitem() #随机删除数组中的值
改:
dict_fruit["apple"] = "苹果1"
查找:
dict_fruit["apple"] #如果值不存在报错
dict_fruit.get("apple") #get 方法查找如果不存在返回空
dict_fruit.keys() # 列出所有key 的值
dict_fruit.values() # 列出所有value的值
dict_fruit.items() #把key和value 放到元组里面
dict_fruit.update(res) #把res字典填充到dict_update中有key的值覆盖
dict_fruit.setdefault(2,3) #创建新的key 如果创建的key字典中有则返回原来key的值
dict.fromkeys(["a","b","c"],"xhl") #批量生成相同value的字典
-
Python中函数的用法
2021-01-21 22:43:08Python中的函数用法。 一.函数的定义 在某些编程语言当中,函数声明和函数定义是区分开的(在这些编程语言当中函数声明和函数定义可以出现在不同的文件中,比如C语言),但是在Python中,函数声明和函数定义是视为... -
python replace函数用法_python pandas replace函数
2021-03-05 12:34:441.基本结构:df.replace(to_replace, value) 前面是需要替换的值,后面是替换后的值。这样会搜索整个DataFrame, 并将所有符合条件的元素全部替换。进行上述操作之后,其实原DataFrame是并没有改变的。改变的只是一个... -
python中complex函数的用法_Python 内置函数complex详解
2021-01-29 03:43:47英文文档:class complex([real[, imag]])Return a complex number with the value real + imag*1j or convert a string or number to a complex number. If the first parameter is a string, it will be ... -
python输出函数使用_Python print()函数高级用法
2020-12-03 13:00:241.前面使用 print() ...print() 函数的详细语法格式如下:print (value,...,sep='',end='\n',file=sys.stdout,flush=False)从上面的语法格式可以看出,value 参数可以接受任意多个变量或值,因此 print() 函数完全... -
python中sub函数用法_Python pandas.DataFrame.sub函数方法的使用
2020-12-06 08:10:29DataFrame.sub(other,axis='columns',level=None,fill_value=None)[source]获取DataFrame和其他元素的减法(二进制运算符sub)。与等效,但支持用fill_value替换输入之一中的丢失数据。rsub是反向版本。dataframe - ... -
python define函数用法_php define函数的用法是什么
2021-03-17 01:14:31php define函数的用法:【define()】函数定义一个常量,语法为【define(name,value,case_insensitive)】,定义一个大小写敏感的常量,代码为【define("GREETING","Hello 】。本教程操作环境:windows7系统、PHP5.6版... -
python中bool函数的用法_python函数之bool([x])用法详解
2021-02-03 08:50:25bool([x])英文说明:Convert a value to a Boolean, using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True. bool is also a class, which is a ... -
Python之eval函数的用法
2019-01-12 15:50:38Python之eval函数的用法 功能:将字符串str当成有效的表达式来求值并返回计算结果。 语法: eval(source[, globals[, locals]]) -> value 参数: source:一个Python表达式或函数compile()返回的代码... -
python中function函数的用法_Python中Function(函数)和methon(方法)
2020-12-19 08:29:47在Python中,对这两个东西有明确的规定:函数function —— A series of statements which returns some value toa caller. It can also be passed zero or more arguments which may beused in the execution of ... -
python 3 print函数用法实例详解_python3的print()函数的用法图文讲解
2021-03-17 00:49:40Python 3 print 函数 基础代码1、print语法格式print()函数具有丰富的功能,详细语法格式如下:print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)默认情况下,将值打印到流或sys.stdout。... -
python中pivot函数用法_Python pandas.DataFrame.pivot_table函数方法的使用
2021-01-29 04:19:56DataFrame.pivot_table(self,values=None,index=None,columns=None,aggfunc='mean',fill_value=None,margins=False,dropna=True,margins_name='All',observed=False)→ 'DataFrame'[source]创建电子表格样式的pivot ... -
python的max函数怎么用_python奇技淫巧——max/min函数的用法
2020-12-08 07:54:19本文以max()为例,对min/max内建函数进行说明源码def max(*args, key=None): # known special case of max"""max(iterable, *[, default=obj, key=func]) -> valuemax(arg1, arg2, *args, *[, key=func]) -> ... -
python中bool函数的用法_python3实战python函数每日一讲 - bool([x])
2020-12-10 21:23:36bool([x])英文说明:Convert a value to a Boolean, using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True. bool is also a class, which is a ... -
python中insert()函数的用法_Python Pandas dataframe.insert()用法及代码示例
2021-01-12 02:12:39Pandas 插入方法允许用户在 DataFrame 或系列(1-D DataFrame )中插入列。也可以通过以下方法将一列手动插入 DataFrame 中,...用法:DataFrameName.insert(loc, column, value, allow_duplicates = False)参数:loc... -
python time函数用法_python – 如何使用dataframe between_time()函数
2020-12-05 23:00:24示例 – 我使用评论中的信息:import pandas as pdimport StringIOimport datetimedata = '''time --- value1984-12-12 14:08:00 --- 11984-12-12 14:25:00 --- 21984-12-12 14:47:00 --- 41984-12-12 16:37:00 --- ... -
python中的isinstance()函数的用法
2019-10-28 14:56:33今天学习python中字节串(bytes)和字符串(str)相互转化的过程中,需要将输入的内容转化为字符串或者字节串。将上面的需求别写成相应的函数 1.首先将输入转化为字符串 # 转化为字符串 def to_str(bytes_or_str): if... -
python常见内置函数的用法
2018-12-11 16:34:22多用于在for循环中得到计数,可以同时获得索引和值,即需要index和value值的时候可以使用。 >>> country=["China","America","Korea","Russia",&... -
Python reduce()函数的用法详解
2020-02-17 10:32:41今天刷题时又见识到了大佬精简的代码,所以特地学习了一下reduce的用法,在此记录。 reduce的语法格式 reduce(function, sequence[, initial]) -> value reduce函数接受一个function和一串sequence,并返回单一的... -
python奇技淫巧——max/min函数的用法
2019-03-06 22:50:15python奇技淫巧——max/min函数的用法 本文以max()为例,对min/max内建函数进行说明 源码 def max(*args, key=None): # known special case of max “”" max(iterable, *[, default=obj, key=func]) ->... -
python3的print()函数的用法图文讲解
2020-08-05 18:24:00Python 3 print 函数 基础代码 1、print语法格式 print()函数具有丰富的功能,详细语法格式如下: print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) 默认情况下,将值打印到流或sys.stdout。... -
Python中min/max函数的用法
2019-05-09 23:54:35本篇以min()函数为例进行说明,max()同理。 先来看看源码 def min(*args, key=None): # known special case of min """ min(iterable, *[, default=obj, key=func]) -> value min(arg1, arg2, *args, *[, key... -
python里的enumerate函数用法
2019-10-23 13:47:53Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身: >>> for i, value in enumerate(['A', 'B', 'C']): ... print(i, value) ... 0 A 1 B 2 C ... -
python print用法 编码_17.Python print()函数高级用法
2021-01-28 18:11:16print() 函数的详细语法格式如下:print (value,...,sep='',end='\n',file=sys.stdout,flush=False)从上面的语法格式可以看出,value 参数可以接受任意多个变量或值,因此 print() 函数完全可以... -
pythonprint函数输出1到n_Python print()函数高级用法
2021-01-15 03:01:06print() 函数的详细语法格式如下:print(value,...,sep='',end='\n',file=sys.stdout,flush=False)从上面的语法格式可以看出,value 参数可以接受任意多个变量或值,因此 print() 函数完全可以...