【发布时间】:2020-10-28 01:38:06
【问题描述】:
我有一个如下所示的 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 排序吗? IE。 feature 之后的第一列将是 20192,然后是 20193,依此类推。
【问题讨论】:
标签: python-3.x pandas