【问题标题】:Pandas apply returns indexing error even though indices look to be correct即使索引看起来正确,Pandas 也会应用返回索引错误
【发布时间】:2023-04-02 13:59:01
【问题描述】:

我遇到了一个索引错误,我不知道如何解决它:IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match). 我不明白它为什么会抛出这个错误,因为display() 调用中显示的索引是一致的。

我尝试了答案here中的双括号,但它不起作用。

下面的可重复示例基于真实代码的高度简化版本。错误在最后一行抛出。

使用 Python 3.7。

import pandas as pd

def myfcn(row, data, delta=200):
    # do things here that add a new column
    # and only populate column
    # for the true indices in "pts"
    print(row)

col1 = ['A','A','A','A','B','B']
col2 = [-1,2.1,7,0,3,4]
col3 = ['yes','yes','no','yes','yes','no']
df = pd.DataFrame(list(zip(col1, col2, col3)), columns =['grp', 'value', 'descrip'])

mask = (
        df['grp'].isin(['A', 'B']) &
        (df['value'] > 0)
)

subset = df[mask]
pts = subset['descrip'] == 'yes'
display(df)
display(subset)
display(pts)

df[pts].apply(myfcn, axis=1, args=(subset, ))
# also tried df[[pts]].apply(myfcn, axis=1, args=(subset, ))

预期输出:

【问题讨论】:

  • 使用布尔索引时,索引器的大小必须与索引相同。您在这里混合了两种技术:屏蔽和布尔索引。选择一种策略并坚持下去,它应该可以解决问题。
  • myfnc 的目的是什么?没有代码。新列是如何确定的
  • @GoldenLion 对于产生最小可重复示例的目的并不重要。 stackoverflow.com/help/minimal-reproducible-example
  • 代码不可重复。分配到第 1 行和第 4 行的 200 是随机的,没有代码

标签: python pandas indexing apply


【解决方案1】:

问题是您试图用pts 索引df,这是一个包含真/假值的熊猫系列。当您使用方括号将某些内容传递给 df 时,默认行为是尝试使用传递的对象中的索引来选择 DataFrame 的列,这在这种情况下没有任何意义。

如果您想使用在pts 对象中创建的条件仅选择dfpts 为True 的行,您可以这样做:

df.loc[pts[pts].index]

虽然这有点笨拙,但您可以在示例中使用完整的条件集进行索引(如果这是您在实际用例中需要的):

df.loc[
    (df['grp'].isin(['A', 'B'])) &
    (df['value'] > 0) & 
    (df['descrip'] == 'yes')
]

【讨论】:

    【解决方案2】:

    检查分配loc

    df.loc[pts.index[pts],'new_col'] = 200
    df
    Out[86]: 
      grp  value descrip  new_col
    0   A   -1.0     yes      NaN
    1   A    2.1     yes    200.0
    2   A    7.0      no      NaN
    3   A    0.0     yes      NaN
    4   B    3.0     yes    200.0
    5   B    4.0      no      NaN
    

    【讨论】:

      猜你喜欢
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 1970-01-01
      相关资源
      最近更新 更多