【发布时间】: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