首页 文章

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

提问于
浏览
1

所以我有一个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 回答

  • 0

    您使用 at 的点,数据是带有整数索引的Pandas系列,这就是您得到上述错误的原因 .

    #ValueError: At based indexing on an integer index can only have integer indexers
    

    如果检查数据的索引,您将看到值为2的索引

    df[df.foo == 222].loc[:,'bar'].index
    
    #Int64Index([2], dtype='int64')
    

    正如coldspeed所提到的,正确的方法之一

    df.loc[df.foo == 222].at[2,'bar']
    
    #555
    
  • 0

    您可以使用 values 轻松获取值

    df2.loc[1,'Name'] = df[df.foo == 222]['foo'].values
    df2
    
    #   Name
    # 1 222
    
  • 0

    使用带有布尔掩码的 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 isn 't. What you should'已经完成了

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

相关问题