【问题标题】:How convert multi value row to columns using pandas?如何使用熊猫将多值行转换为列?
【发布时间】:2020-03-23 14:09:00
【问题描述】:

我用什么函数来转换这个Dataframe:

id name genre

1 Fiml1 action, comedy
2 Fiml2 animation
3 Fiml3 comedy
4 Fiml4 action, animation
5 Fiml5 action
6 Fiml6 animation, comedy

收件人:

id name action animation comedy

1  Fiml1   1       0       1
2  Fiml2   0       1       0
3  Fiml3   0       0       1
4  Fiml4   1       1       0
5  Fiml5   1       0       0
6  Fiml6   0       1       1

此数据框将用于向量空间模型,答案或任何建议?

【问题讨论】:

    标签: python python-3.x pandas dataframe data-science


    【解决方案1】:

    您可以使用pd.concatSeries.str.dummies', ' 作为分隔符:

    df = pd.concat([
        df[['id', 'name']], df['genre'].str.get_dummies(sep=', ')
    ], axis=1)
    
       id   name  action  animation  comedy
    0   1  Fiml1       1          0       1
    1   2  Fiml2       0          1       0
    2   3  Fiml3       0          0       1
    3   4  Fiml4       1          1       0
    4   5  Fiml5       1          0       0
    5   6  Fiml6       0          1       1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-07
      • 2020-10-05
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      • 2019-05-22
      相关资源
      最近更新 更多