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

新手上路,请多包涵

所以我有一个 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 许可协议

阅读 3.1k
2 个回答

at 与布尔掩码一起使用被认为是错误的形式,除非您可以 100% 保证掩码中只有一行为真(否则, at 失败)。

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

 df.loc[df.foo == 222, 'bar'].values[0]
555

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

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

2    555
Name: bar, dtype: int64

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

df[df.foo == 222].at[2, 'bar']
555

原文由 cs95 发布,翻译遵循 CC BY-SA 4.0 许可协议

.at 将使用标签索引,而不是位置索引。

例子:

 df.at(3,'ColName')

返回第 3 行的值 ColName

原文由 Shifu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题