首页 > 解决方案 > 如何对熊猫中的列进行分组?

问题描述

我有这样的DataFrame:

   Jan Feb Jan.01 Feb.01
0   0   4   6     4
1   2   5   7     8 
2   3   6   7     7

如何将其分组以获得此结果?我必须使用哪些功能?

      2000     2001
   Jan Feb Jan.01 Feb.01
0   0   4   6     4
1   2   5   7     8 
2   3   6   7     7

标签: pythonpython-3.xpandas

解决方案


我认为这会做

df

    Jan                 Feb                 Jan.01  Feb.01
0   2016-01-01 00:00:00 2016-01-02 00:00:00      2     413
1   2016-01-02 01:00:00 2016-01-03 01:00:00      1     414
2   2016-01-03 02:00:00 2016-01-04 02:00:00      2     763
3   2016-01-04 03:00:00 2016-01-05 03:00:00      1     837
4   2016-01-05 04:00:00 2016-01-06 04:00:00      2     375


level1_col = pd.Series(df.columns).str.split('.').apply(lambda x: 2000+int(x[1]) if len(x) == 2 else 2000)
level2_col = df.columns.tolist()
df.columns = [level1_col, level2_col]
df

    2000                                    2001
    Jan                 Feb                 Jan.01  Feb.01
0   2016-01-01 00:00:00 2016-01-02 00:00:00      2     413
1   2016-01-02 01:00:00 2016-01-03 01:00:00      1     414
2   2016-01-03 02:00:00 2016-01-04 02:00:00      2     763
3   2016-01-04 03:00:00 2016-01-05 03:00:00      1     837
4   2016-01-05 04:00:00 2016-01-06 04:00:00      2     375

df[2000]

    Jan                 Feb
0   2016-01-01 00:00:00 2016-01-02 00:00:00
1   2016-01-02 01:00:00 2016-01-03 01:00:00
2   2016-01-03 02:00:00 2016-01-04 02:00:00
3   2016-01-04 03:00:00 2016-01-05 03:00:00
4   2016-01-05 04:00:00 2016-01-06 04:00:00

推荐阅读