gpt4 book ai didi

python - pandas 将数据框转换为 pivot_table,其中 index 是排序值

转载 作者:行者123 更新时间:2023-12-04 08:29:37 24 4
gpt4 key购买 nike

我有以下数据框:

   site   height_id  height_meters
0 9 c3 24
1 9 c2 30
2 9 c1 36
3 3 c0 18
4 3 bf 24
5 3 be 30
6 4 10 18
7 4 0f 24
8 4 0e 30
我想将其转换为以下此列索引是“站点”的值,值是“height_meters”,我希望它按值的顺序索引(我在互联网上查看并没有找到类似的东西.. . 尝试分组并制作一些数据透视表但没有成功):
   9   3   4
0 24 18 18
1 30 24 24
2 36 30 24
数字之间的差距是不必要的......
这是df
my_df = pd.DataFrame(dict(
site=[9, 9, 9, 3, 3, 3, 4, 4, 4],
height_id='c3,c2,c1,c0,bf,be,10,0f,0e'.split(','),
height_meters=[24, 30, 36, 18, 24, 30, 18, 24, 30]
))

最佳答案

您可以使用 GroupBy.cumcount 用于列的计数器 site :

print (my_df.groupby('site').cumcount())

0 0
1 1
2 2
3 0
4 1
5 2
6 0
7 1
8 2
dtype: int64
您可以将其转换为 indexsite通过 Series.unstack 列和 reshape :
df = my_df.set_index([my_df.groupby('site').cumcount(), 'site'])['height_meters'].unstack()
print (df)
site 3 4 9
0 18 18 24
1 24 24 30
2 30 30 36
DataFrame.pivot 类似的解决方案和由 cumcount 创建的列:
df = my_df.assign(new=my_df.groupby('site').cumcount()).pivot('new','site','height_meters')
print (df)
site 3 4 9
new
0 18 18 24
1 24 24 30
2 30 30 36
如果订单很重要,请添加 DataFrame.reindex 按列 site 的唯一值:
df = (my_df.set_index([my_df.groupby('site').cumcount(), 'site'])['height_meters']
.unstack()
.reindex(my_df['site'].unique(), axis=1))
print (df)
site 9 3 4
0 24 18 18
1 30 24 24
2 36 30 30
最后删除 site ( new ) 列和索引名称可以使用 DataFrame.rename_axis :
df = df.rename_axis(index=None, columns=None)
print (df)
3 4 9
0 18 18 24
1 24 24 30
2 30 30 36

关于python - pandas 将数据框转换为 pivot_table,其中 index 是排序值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65089935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com