Python 从数据帧中获取单个值
我有一个数据帧a:Python 从数据帧中获取单个值,python,pandas,Python,Pandas,我有一个数据帧a: 's' 'S' 'T' 0 'abc' 'a' 12 1 'def' 'b' 15 2 'abc' 'b' 1.4 现在我想得到'T'的值,其中's'='abc'和's'='b' 所以我试着: idx = (A['s'] == 'abc') & (A['S'] == 'b') 但是我明白了。get_value()是去润滑的,并且: number = A.at[idx,'T'] 给出此错误
's' 'S' 'T'
0 'abc' 'a' 12
1 'def' 'b' 15
2 'abc' 'b' 1.4
现在我想得到'T'的值,其中's'='abc'和's'='b'
所以我试着:
idx = (A['s'] == 'abc') & (A['S'] == 'b')
但是我明白了。get_value()是去润滑的,并且:
number = A.at[idx,'T']
给出此错误:
ValueError: At based indexing on an integer index can only have integer indexers
编辑:
返回数据帧,而不是值(整数或浮点)
执行此操作时:
number2 = 1.3
if (number != number2):
我得到:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
过滤后,您将获得一个项目系列,因此对于选择第一个值,可以使用iat:
number = A.loc[idx,'T'].iat[0]
print (number)
14
但如果掩码返回更多值,则获取:
print (A)
s S T
0 abc a 12
1 abc b 15
2 abc b 14
idx = (A['s'] == 'abc') & (A['S'] == 'b')
print (idx)
0 False
1 True
2 True
dtype: bool
number = A.loc[idx,'T']
print (number)
1 15
2 14
Name: T, dtype: int64
这里可以使用相同的aproach-选择条件的第一个值:
number = A.loc[idx,'T'].iat[0]
print (number)
15
上面将抛出一个未定义idx的错误,访问索引的默认方式是dataframe.index,而不是idx 应该是这样
number = A.loc[A.index,'T'].iat[0]
number = A.loc[idx,'T'].iat[0]
print (number)
15
number = A.loc[A.index,'T'].iat[0]