我得到了一个索引错误,我不知道如何修复它: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, ))
问题是您试图用
pts
索引df
,这是一个包含真/假值的熊猫系列。当您使用方括号将某些内容传递给df
时,默认行为是尝试使用传递的对象中的索引来选择数据帧的列,这在本例中没有任何意义如果要使用在
pts
对象中创建的条件仅选择df
中pts
为True的行,可以执行以下操作:df.loc[pts[pts].index]
尽管这有点笨拙,您可以在示例中使用完整的条件集编制索引(如果您在实际用例中需要这样做的话):
使用assign
loc
检查相关问题 更多 >
编程相关推荐