首页 > 解决方案 > Pandas DataFrame 按不等列顺序旋转

问题描述

我有一个看起来像这样的数据框:

df=pd.DataFrame({'Machine':['A','A','B','B','B'],
                 'Date':['1/1/2020','4/5/2020','4/1/2020','4/3/2020','5/1/2020'],
                'Production':[5,9,44,13,34],
                })

  Machine      Date  Production
0       A  1/1/2020           5
1       A  4/5/2020           9
2       B  4/10/2020         44
3       B  4/3/2020          13
4       B  5/1/2020          34

我希望将其转换为:

    A   B
0   5  13
1   9  44
2      34

索引只是按顺序排列的日期排名。

有没有办法在不先创建排名列的情况下做到这一点?

raw_data["RANK"] = raw_data.groupby('Machine')["Date"].rank(method="first", ascending=True)
new_data = raw_data.pivot(columns = 'Machine', values = 'Production', index = 'RANK')

标签: pythonpandaspivot

解决方案


推荐阅读