所以我有一个 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
我假设最后一行抛出该错误,因为 df[df.foo == 222]['foo']
是 Series
:
2 222
Name: foo, dtype: int64
所以我试图获得价值本身。我使用了 .at
得到了这个:
print(df[df.foo == 222].loc[:,'bar'].at['bar'])
#ValueError: At based indexing on an integer index can only have integer indexers
根据我的阅读,它是 iat
使用整数索引器和 at
使用标签和整数,那么这里发生了什么?
原文由 Nathan Tew 发布,翻译遵循 CC BY-SA 4.0 许可协议
将
at
与布尔掩码一起使用被认为是错误的形式,除非您可以 100% 保证掩码中只有一行为真(否则,at
失败)。最好的办法是使用
loc
并取第一个结果。作为参考,
at
不起作用,因为返回具有索引的单行系列[2]
:此时,
at['bar']
没有意义,因为它在索引中搜索“bar”,而bar
不是。你应该做的是