首页 > 解决方案 > 在透视后对列名称进行排序以升序

问题描述

我有一个 Spark 数据框,如下所示:

+----+-----+-------------+---+
|year|month|feature      |cnt|
+----+-----+-------------+---+
|2019|2    |Feature1     |2  |
|2019|2    |Feature2     |5  |
|2019|2    |Feature3     |54 |
|2019|2    |Feature4     |75 |
|2019|2    |...          |1  |
|2019|2    |...          |85 |
|2019|2    |...          |77 |
|2019|2    |...          |124|
|2019|2    |...          |6  |
|2019|2    |...          |362|
|2019|2    |...          |74 |
|2019|2    |...          |10 |
|2019|3    |Feature1     |10 |
|2019|3    |Feature2     |5  | 
...

我可以成功地将数据框转换为 Pandas 并将年 + 月的组合转换为列:

monthly_df = monthly_counts.toPandas()
monthly_df['yearM'] = monthly_df['year'].astype(str) + monthly_df['month'].astype(str)
del monthly_df['year']
del monthly_df['month']

monthly_pv = pd.pivot_table(monthly_df, values = 'cnt', index=['feature'], columns='yearM').reset_index()
monthly_pv

问题是列顺序变成了这样(尽管原始数据帧按 asc 排序):

yearM | feature | 201910 | 201911 | 201912 | 20192 | 20193 | 20194 | 20195 | 20196 | 20197 ...

无论如何,我可以让列名在透视表中按 asc 排序吗?即之后的第一列feature20192紧随其后20193,依此类推。

标签: python-3.xpandas

解决方案


问题是您命名列的方式使它们按字母顺序以错误的顺序排序。20191后跟201910, 201911,201912然后20192. 为了解决这个问题,您可以在个位数月份中添加一个零:

monthly_df = monthly_counts.toPandas().assign(day=1)
monthly_df['yearM'] = pd.to_datetime(monthly_df[['year','month','day']]).dt.strftime('%Y%m')
del monthly_df['year']
del monthly_df['month']
del monthly_df['day']

monthly_pv = pd.pivot_table(monthly_df, values = 'cnt', index=['feature'], columns='yearM').reset_index()
monthly_pv

推荐阅读