如何对熊猫中的列进行分组?

时间:2019-01-11 04:20:34

标签: python python-3.x pandas

我有这样的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

1 个答案:

答案 0 :(得分:0)

我认为这样做

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