Pandas 应用 returns 索引错误,即使索引看起来是正确的

Pandas apply returns indexing error even though indices look to be correct

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

我在答案中尝试了双括号,但没有用。

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

使用 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, ))

预期输出:

检查分配 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

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

如果要将在 pts 对象中创建的条件用于 select 仅 dfpts 为 True 的行,您可以执行以下操作:

df.loc[pts[pts].index]

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

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