【问题标题】:Pandas .at throwing ValueError: At based indexing on an integer index can only have integer indexersPandas .at 抛出 ValueError:基于整数索引的索引只能有整数索引器
【发布时间】:2019-05-11 06:53:43
【问题描述】:

所以我有一个 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 同时使用标签和整数,那么这里发生了什么?

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

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

    df.at(3,'ColName')
    

    返回第三行的ColName 值。

    【讨论】:

      【解决方案2】:

      您使用 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
      

      【讨论】:

        【解决方案3】:

        将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
        

        【讨论】:

        • @NathanTew 好吧,如果您考虑一下;这说得通。 Pandas 假设您在使用这些索引器函数时知道自己在做什么,尽管我承认这条学习曲线存在非零梯度。
        • 但是说at 只能有整数索引器本身并不是不正确的,因为它没有?
        • @NathanTew 但是df[df.foo == 222].loc[:,'bar'] 确实只有整数索引,所以当你尝试使用非整数索引时它自然会抱怨(.at['bar'])。跨度>
        • @NathanTew (Last ping, promise) 谢谢你的接受;如果答案有帮助,您也可以投票赞成。单击答案左侧“0”上方的三角形。谢谢!
        【解决方案4】:

        您可以使用values轻松获取值

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

        【讨论】:

        • 谢谢,这有帮助,但我的主要问题是为什么 .at 不起作用
        • 将完整索引传递给at,如at.[row_idx, col_idx]
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-17
        • 2016-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-14
        • 1970-01-01
        相关资源
        最近更新 更多