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

2024-09-28 05:26:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

enter image description here

预期输出:
enter image description here


Tags: andofthedfhereas错误display
2条回答

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

如果要使用在pts对象中创建的条件仅选择dfpts为True的行,可以执行以下操作:

df.loc[pts[pts].index]

尽管这有点笨拙,您可以在示例中使用完整的条件集编制索引(如果您在实际用例中需要这样做的话):

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

使用assignloc检查

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

相关问题 更多 >

    热门问题