Python dataframe取单元值

取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_loc
    return self._engine.get_loc(casted_key)
  File "pandas\_libs\index.pyx", line 76, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 5206, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 0

The 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_value
    series = self._get_item_cache(col)
  File "D:\Program Files\Python371\lib\site-packages\pandas\core\frame.py", line 3884, in _get_item_cache
    loc = self.columns.get_loc(item)
  File "D:\Program Files\Python371\lib\site-packages\pandas\core\indexes\base.py", line 3363, in get_loc
    raise 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_key
    raise ValueError("iAt based indexing can only have integer indexers")
ValueError: iAt based indexing can only have integer indexers
>>> 
  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值