python - How to Group then Transpose Dataframe without summarization
问题描述
I need to Group ID from below Dataframe then Transpose the Value with new Dynamic incremental Header
data = {'ID': ['A', 'B', 'B', 'B', 'C', 'C', 'D', 'D', 'D', 'D'],
'Value': [30, 760, 740, 755, 1 ,4, 56, 34, 76, 12]}
df = pd.DataFrame(data,columns=['ID', 'Value'])
ID Value
0 A 30
1 B 760
2 B 740
3 B 755
4 C 1
5 C 4
6 D 56
7 D 34
8 D 76
9 D 12
I need the output to be something like this
ID Value1 Value2 Value3 Value4
0 A 30
1 B 760 740 755
2 C 1 4
3 D 56 34 76 12
解决方案
The following will get you well on your way there:
df.pivot(columns='ID').T.fillna('').reset_index().drop(columns='level_0')
Producing:
ID 0 1 2 3 4 5 6 7 8 9
0 A 30
1 B 760 740 755
2 C 1 4
3 D 56 34 76 12
推荐阅读
- python - 将列表添加到数据帧,同时按长度 fo DF 连接
- highcharts - 带堆积柱的 Highchart 组合图
- javascript - 如果日期值早于 30 天,则隐藏 JSON 元素
- javascript - 如何通过单击更改按钮样式和嵌套在按钮中的图标样式?
- sql - 如何在 Oracle 中重复查询
- javascript - 如何使用 Intl.NumberFormat 格式化货币?
- sql - SQL - 创建表和查询 - 正确吗?
- javascript - 在 javascript 中为 var 赋值的语法错误
- python - python中多个模块的错误处理
- javascript - FullCalendar 4.0.0-beta.2 从另一个非日历函数调用 eventRender 函数