python panda:在列中查找特定字符串并填充与该字符串匹配的列

Kir*_*tin 0 python pandas

我有一个包含多个列的数据框.其中一个充满了由|分隔的电影的"流派",我在其他几个部分拆分了这一列,以获得每个填充分割值的X列.然而,我需要的是每个"流派"有1列,由1或0填充,具体取决于列的标题是在名义类型列中还是在其中一个分割列中找到.我将我的数据框设置如下:

    df = pd.DataFrame({'A': ['drama|Action', 'Drama', 'Action'], 'A_split1': ['Drama', 'Drama', 'Action'],'A_split2': ['Action', 'None', 'None'],'Drama': [0, 0, 0], 'Action': [0, 0, 0], 'Western': [0, 0, 0]},
                  index = ['a1', 'a2', 'a3'])
    df
Run Code Online (Sandbox Code Playgroud)

但我没有找到如何检查标头的名称是否在一个字符串内添加1或0.

jez*_*ael 6

我认为你需要pop提取列str.get_dummiesjoin原始的:

df = pd.DataFrame({'A': ['Drama|Action', 'Drama', 'Action'], 'B':range(3)},
                  index = ['a1', 'a2', 'a3'])
print (df) 
               A  B
a1  Drama|Action  0
a2         Drama  1
a3        Action  2

df = df.join(df.pop('A').str.get_dummies())
print (df)
    B  Action  Drama
a1  0       1      1
a2  1       0      1
a3  2       1      0
Run Code Online (Sandbox Code Playgroud)

如果想要原始栏目:

df = df.join(df['A'].str.get_dummies())
print (df)
               A  B  Action  Drama
a1  Drama|Action  0       1      1
a2         Drama  1       0      1
a3        Action  2       1      0
Run Code Online (Sandbox Code Playgroud)