微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

IndexError:布尔索引与索引数组不匹配

如何解决IndexError:布尔索引与索引数组不匹配

我正在尝试以特定方式解决此问题。希望得到有关如何进行的指示。

我有 df1,即:

df1 = pd.DataFrame({'Model': ['model1','model2','model3']})

然后是df2,即:

model1 = pd.DataFrame({'Model' : ['model1','model1','model1'],'Rule' : ['High','Low','High'],'Name' : ['A','B','C']})
model2 = pd.DataFrame({'Model' : ['model2','model2'],'Rule' : ['Low','Name' : ['B','D','F']})
model3 = pd.DataFrame({'Model' : ['model3','model3','model3'],'High','Name' : ['D','E','F']})
df2 = [model1,model2,model3]

然后是df3,就是:

df3 = pd.DataFrame({'Name' : ['A','C','F'],'model1' : [np.nan,np.nan,],'High1' : [np.nan,'Low1' : [np.nan,'model2' : [np.nan,'High2' : [np.nan,'Low2' : [np.nan,'model3' : [np.nan,'High3' : [np.nan,'Low3' : [np.nan,]})

我希望输出如下所示:

df3 = pd.DataFrame({'Name' : ['A','model1' : ['Yes','Yes','High1' : [0,]})

这是我的代码

for model in df1['Model']:
            col_index = df3.columns.get_loc(model)
            df3.iloc[df3['Name'].isin(df2[model]['Name']),col_index] = 'Yes'
            df3.iloc[df3['Name'].isin(df2[model]['Name']) & (df2[model]['Rule']=='High'),col_index+1] = 0
            df3.iloc[df3['Name'].isin(df2[model]['Name']) & (df2[model]['Rule']=='Low'),col_index+2] = 0

这给了我以下错误

IndexError: boolean index did not match indexed array along dimension 0; dimension is 389 but corresponding boolean dimension is 853

我假设这是由 (df2[model]['Rule']=='High') 引起的,其中 'High' 是一个标量。

注意:我希望代码使用 for 循环来解决这个问题,如上面的代码所示,因为它有助于我正在做的其他事情。

解决方法

我认为你只是在寻找支点

df3.pivot('Name','Property','Name').notnull()

Property   colA   colB   colC
Name                         
A          True   True  False
B         False  False   True
C          True  False   True

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。