【问题标题】:python - binary encoding of comma separated string columnpython - 逗号分隔的字符串列的二进制编码
【发布时间】:2018-01-12 09:41:53
【问题描述】:

有人可以帮助我对类似于以下示例的数据进行二进制编码:

df = pd.DataFrame({'_id': [1,2,3],
                   'test': ['one,two,three', 'one,two', 'two']})

print(df)

   _id           test
0    1  one,two,three
1    2        one,two
2    3            two

到这里:

df_result = pd.DataFrame({'id': [1,2,3],
                          'one': [1,1,0],
                          'two': [1,1,1],
                          'three': [1,0,0]})
print(df_result)

   id  one  three  two
0   1    1      1    1
1   2    1      0    1
2   3    0      0    1

任何帮助将不胜感激! 谢谢

【问题讨论】:

    标签: python pandas data-manipulation


    【解决方案1】:

    使用str.get_dummies()

    In [58]: df.test.str.get_dummies(',')
    Out[58]:
       one  three  two
    0    1      1    1
    1    1      0    1
    2    0      0    1
    

    如果需要,使用join 将结果还原为原始结果。

    In [62]: df.join(df.test.str.get_dummies(','))
    Out[62]:
       _id           test  one  three  two
    0    1  one,two,three    1      1    1
    1    2        one,two    1      0    1
    2    3            two    0      0    1
    

    或者,pd.concat

    In [63]: pd.concat([df, df.test.str.get_dummies(',')], axis=1)
    Out[63]:
       _id           test  one  three  two
    0    1  one,two,three    1      1    1
    1    2        one,two    1      0    1
    2    3            two    0      0    1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多