首页 > 解决方案 > 如何将单列数据转换为python数据框中的多列?

问题描述

我有一个数据框 ( df),其中的列col1有很多行,并且有一些行带有一个公共字符串 ( Collection of numbers are),并以不同的数字 ( 001, 002, 005) 结尾。我想提取两个字符串(Collection of numbers are 002to Collection of numbers are 003)之间的行并将它们分配给具有相同行名(Collection of numbers are 002)的新列

    col1
0   Collection of numbers are 002
1   53
2   20
3   56
4   Collection of numbers are 003
5   236
6   325
7   Collection of numbers are 005
8   96
9   23
10  63

我想将上面的数据框转换为以下格式。

0   Collection of numbers are 002   Collection of numbers are 003   Collection of numbers are 005
1   53                              236                              96
2   20                              325                              23
3   56                                                               63

注意:没有重复的数字

标签: pythonpython-3.xpandas

解决方案


我们可以尝试ffill使用str.split

df['headers'] = df['col1'].str.extract('(Collection.*)').ffill()


df1 = df[~df['col1'].str.contains('Collection')].copy()


df1.groupby('headers').agg(','.join)['col1'].str.split(',',expand=True).T.rename_axis('',axis='columns')

出去:

  Collection of numbers are 002 Collection of numbers are 003  \
0                            53                           236   
1                            20                           325   
2                            56                          None   

  Collection of numbers are 005  
0                            96  
1                            23  
2                            63  

推荐阅读