【问题标题】:python panda: find a specific string in a column and fill the column matching the stringpython panda:在列中查找特定字符串并填充与该字符串匹配的列
【发布时间】:2018-08-04 07:41:21
【问题描述】:

我有一个包含几列的数据框。其中一个充满了由 | 分隔的电影的“流派”,我已将此列拆分为其他几个列,以获得 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

但我没有找到如何检查标题名称是否在字符串中以添加 1 或 0。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我认为您需要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
    

    如果想要原始列:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-17
      • 1970-01-01
      • 2019-06-14
      • 2013-06-18
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      相关资源
      最近更新 更多