【问题标题】:Pandas: Convert column with more than one string into rows with Pandas :Pandas:使用 Pandas 将具有多个字符串的列转换为行:
【发布时间】:2022-08-13 21:38:38
【问题描述】:

我正在从谷歌表中收集一些数据,但我需要将包含多个字符串的一列转换为一行。但是每个单元格可以有多个字符串,并且我想将每个字符串放在一行中

我有这个数据框

import pandas as pd
df = pd.DataFrame({\'Name\': [\'Bob\', \'John\', \'Ric\'], 
                           \'Submitted At\': [\'2022/08/12 23:56:42\', \'2022/08/12 23:56:42\', \'2022/08/12 23:56:42\'], 
                           \'Class\': [\'Math,English,History\', \'English,History\', \'Math, Chemistry\']})
    
print(df)


   Name         Submitted At                 Class
0   Bob  2022/08/12 23:56:42  Math,English,History
1  John  2022/08/12 23:56:42       English,History
2   Ric  2022/08/12 23:56:42       Math, Chemistry

我想变成这个

我正在尝试这样做,但没有奏效

df2 = df.join(df[\'Class\'].str.split(\',\', expand=True).add_prefix(\'Class\'))

print(df2.melt(id_vars=[\'Submitted At\', \'Name\'], var_name=df2.iloc[:, 2:6]))


ValueError: Unable to coerce to Series, length must be 4: given 2

请问你能帮帮我吗?

谢谢 里卡多

    标签: python pandas pandas-melt


    【解决方案1】:

    你可以试试

    out = (df.assign(Class=df['Class'].str.split(','))
           .explode('Class', ignore_index=True))
    
    print(out)
    
       Name         Submitted At       Class
    0   Bob  2022/08/12 23:56:42        Math
    1   Bob  2022/08/12 23:56:42     English
    2   Bob  2022/08/12 23:56:42     History
    3  John  2022/08/12 23:56:42     English
    4  John  2022/08/12 23:56:42     History
    5   Ric  2022/08/12 23:56:42        Math
    6   Ric  2022/08/12 23:56:42   Chemistry
    

    【讨论】:

      猜你喜欢
      • 2016-08-30
      • 2020-10-22
      • 2021-03-09
      • 2022-11-19
      • 2016-09-17
      • 2020-11-20
      • 1970-01-01
      • 2019-01-14
      相关资源
      最近更新 更多