简体   繁体   中英

How to group columns in pandas?

I have DataFrame like this:

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

How can group this for getting this result? What functions i must to use?

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

I think this will do

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM