所以我有一个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
所以我试图获得 Value 本身 . 我使用 .at
得到了这个:
print(df[df.foo == 222].loc[:,'bar'].at['bar'])
#ValueError: At based indexing on an integer index can only have integer indexers
从我使用整数索引器的've read it'和 at
同时使用标签和整数,那么这里发生了什么?
3 回答
您使用
at
的点,数据是带有整数索引的Pandas系列,这就是您得到上述错误的原因 .如果检查数据的索引,您将看到值为2的索引
正如coldspeed所提到的,正确的方法之一
您可以使用
values
轻松获取值使用带有布尔掩码的
at
被认为是坏形式,除非您可以100%保证掩码中只有一行为真(否则,at
失败) .最好的办法是使用
loc
并取第一个结果 .作为参考,
at
不起作用,因为返回带有索引[2]
的单行系列:在这一点上,
at['bar']
没有意义,因为它在索引中搜索"bar"并且bar
isn 't. What you should'已经完成了