取dataframe某行某列所指的单元值
代码准备:
环境平台:Python 3.7.1 -IDLE Shell
>>> import pandas as pd
>>> df = pd.DataFrame({'Name': ['Tom', 'Jim', 'Lily'], 'Age': [20, 18, 22], 'Gender': ['Male', 'Male', 'Female']})
注:部分参考了:https://www.python100.com/html/116332.html
使用.at函数(行列-按索引名)
>>> value = df.at[1, 'Age']
>>> value
18
>>> type(value)
<class 'numpy.int64'>
使用.iat函数,行列-按索引(号)
>>> value = df.iat[1, 0]
>>> value
'Jim'
>>>
错误表达
示例1:
>>> value = df.at[1, 0]
Traceback (most recent call last):File "D:\Program Files\Python371\lib\site-packages\pandas\core\indexes\base.py", line 3361, in get_locreturn self._engine.get_loc(casted_key)File "pandas\_libs\index.pyx", line 76, in pandas._libs.index.IndexEngine.get_locFile "pandas\_libs\index.pyx", line 108, in pandas._libs.index.IndexEngine.get_locFile "pandas\_libs\hashtable_class_helper.pxi", line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_itemFile "pandas\_libs\hashtable_class_helper.pxi", line 5206, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 0The above exception was the direct cause of the following exception:Traceback (most recent call last):File "<pyshell#10>", line 1, in <module>value = df.at[1, 0]File "D:\Program Files\Python371\lib\site-packages\pandas\core\indexing.py", line 2275, in __getitem__return super().__getitem__(key)File "D:\Program Files\Python371\lib\site-packages\pandas\core\indexing.py", line 2222, in __getitem__return self.obj._get_value(*key, takeable=self._takeable)File "D:\Program Files\Python371\lib\site-packages\pandas\core\frame.py", line 3568, in _get_valueseries = self._get_item_cache(col)File "D:\Program Files\Python371\lib\site-packages\pandas\core\frame.py", line 3884, in _get_item_cacheloc = self.columns.get_loc(item)File "D:\Program Files\Python371\lib\site-packages\pandas\core\indexes\base.py", line 3363, in get_locraise KeyError(key) from err
KeyError: 0
示例2
>>> value = df.iat[1, 'Age']
Traceback (most recent call last):File "<pyshell#11>", line 1, in <module>value = df.iat[1, 'Age']File "D:\Program Files\Python371\lib\site-packages\pandas\core\indexing.py", line 2221, in __getitem__key = self._convert_key(key)File "D:\Program Files\Python371\lib\site-packages\pandas\core\indexing.py", line 2299, in _convert_keyraise ValueError("iAt based indexing can only have integer indexers")
ValueError: iAt based indexing can only have integer indexers
>>>