python-3.x - 在透视后对列名称进行排序以升序
问题描述
我有一个 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 排序吗?即之后的第一列feature
将20192
紧随其后20193
,依此类推。
解决方案
问题是您命名列的方式使它们按字母顺序以错误的顺序排序。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
推荐阅读
- openid - OpenId 3 到 OpenId 4 多个颁发者名称
- javascript - Azure AD 身份验证 Ember JS v3.15
- pytorch - 如何正确使用 Pytorch 的 View 功能?
- php - 使用适用于 QuickBooks 的 Consolibyte PHP SDK,如何识别哪个客户端正在从 Web 连接器发送调用?
- swift - 解码错误:typeMismatch - 预期解码字典
但找到了一个字符串/数据 - android - 在启动 Intent 时尝试在空对象引用上调用虚拟方法
- firebase - Firebase 命令在终端中引发错误
- rust - 如何使用 RefCell 在 Deref 实现中指定 Target 类型的生命周期?
- iis-7.5 - WinServer 2008 R2 SP1,IIS 7.5 升级到 TLS 1.2 或 1.3
- sql - 在 SQL Server 中创建逗号分隔列表,但将列表限制为 100 个值