【问题标题】:Sorting column names to be ascending after pivoting在透视后对列名称进行排序以升序
【发布时间】: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


    【解决方案1】:

    问题在于您对列的命名方式使它们按字母顺序以错误的顺序排序。 20191 之后是 201910201911201912,然后是 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
    

    【讨论】:

    • 我似乎遇到了 ValueError :extra keys have been passed to the datetime assemblage: [cnt,feature]
    猜你喜欢
    • 2019-01-04
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 2020-06-22
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    相关资源
    最近更新 更多