python - 如何将单列数据转换为python数据框中的多列?
问题描述
我有一个数据框 ( df
),其中的列col1
有很多行,并且有一些行带有一个公共字符串 ( Collection of numbers are
),并以不同的数字 ( 001, 002, 005
) 结尾。我想提取两个字符串(Collection of numbers are 002
to 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
注意:没有重复的数字
解决方案
我们可以尝试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
推荐阅读
- dataframe - 数组列中所有元素的总和
- sql-server - SQL Server:如何在字符串中查询?
- mysql - 如何在依赖于 IN 运算符的分组查询中实现 LIKE 功能?
- c# - 从依赖注入获取记录器和配置?
- c# - Action 的空引用错误
选项动作 - android - Android 在一个应用程序之间共享数据 - 2 个用户
- python - 如何将数据框转换为整洁的形式(unpivot)?
- discord - Discord.py 机器人说话消息
- php - 如何自定义教义结果?
- ruby-on-rails - DashboardApp::DashboardPageController#show 中的 ActionController::UnknownFormat