Pandas .at 抛出 ValueError:基于整数索引的索引只能有整数索引器

Nat*_*Tew 6 python dataframe python-3.x pandas

所以我有一个 df,我在其中提取一个值以将其存储在另一个 df 中:

import pandas as pd

# Create data set
d = {'foo':[100, 111, 222], 
     'bar':[333, 444, 555]}
df = pd.DataFrame(d)

# Full dataframe:
print(df)

# Shows:
#    bar   foo 
# 0  333   100
# 1  444   111
# 2  555   222

df2=pd.DataFrame()
df2.loc[1,'Name'] = df[df.foo == 222]['foo']

#error: 
ValueError: Incompatible indexer with Series
Run Code Online (Sandbox Code Playgroud)

我假设最后一行抛出该错误,因为df[df.foo == 222]['foo']是一个Series

2    222
Name: foo, dtype: int64
Run Code Online (Sandbox Code Playgroud)

所以我试图获得价值本身。我使用.at并得到了这个:

print(df[df.foo == 222].loc[:,'bar'].at['bar'])

#ValueError: At based indexing on an integer index can only have integer indexers
Run Code Online (Sandbox Code Playgroud)

从我读过的内容来看iat,它使用整数索引器并同时at使用标签和整数,那么这里发生了什么?

cs9*_*s95 6

使用at用布尔面具被认为是不好的形式,除非你能保证100%的面具只有一行是真实的(否则,at失败)。

最好的办法是使用loc并取第一个结果。

df.loc[df.foo == 222, 'bar'].values[0]
555
Run Code Online (Sandbox Code Playgroud)

作为参考,at不起作用,因为返回带有索引的单行系列[2]

df[df.foo == 222].loc[:,'bar']

2    555
Name: bar, dtype: int64
Run Code Online (Sandbox Code Playgroud)

在这一点上,at['bar']没有意义,因为它在索引中搜索“bar”而bar不是。你应该做的是

df[df.foo == 222].at[2, 'bar']
555
Run Code Online (Sandbox Code Playgroud)