首页 > 解决方案 > 如何使用python按日期拆分列

问题描述

df.head(7)
df

Month,ward1,ward2,...ward30
    Apr-19, 20, 30,   45
    May-19, 18, 25,   42
    Jun-19, 25, 19,   35
    Jul-19, 28, 22,   38
    Aug-19, 24, 15,   40
    Sep-19, 21, 14,   39
    Oct-19, 15, 18,   41

至:

Month, ward1
Apr-19, 20  
May-19, 18  
Jun-19, 25  
Jul-19, 28  
Aug-19, 24  
Sep-19, 21  
Oct-19, 15  

Month,ward2 
Apr-19, 30  
May-19, 25  
Jun-19, 19  
Jul-19, 22  
Aug-19, 15  
Sep-19, 14  
Oct-19, 18  

Month, ward30
Apr-19, 45
May-19, 42
Jun-19, 35
Jul-19, 38
Aug-19, 40
Sep-19, 39
Oct-19, 41

python - 如何使用pandas在python中按日期分组?

我有数据框 df ,其中包含一个日期时间和 30 个其他列,我想按日期拆分这些列,这些列附在 pandas 中的每一列中,但我面临一些困难。

标签: python-3.xpandastime-series

解决方案


尝试使用字典理解来保存单独的数据框。

dfs = {col : df.set_index('Month')[[col]] for col in (df.set_index('Month').columns)}

print(dfs['ward1'])

        ward1
Month        
Apr-19     20
May-19     18
Jun-19     25
Jul-19     28
Aug-19     24
Sep-19     21
Oct-19     15

print(dfs['ward30'])

        ward30
Month         
Apr-19      45
May-19      42
Jun-19      35
Jul-19      38
Aug-19      40
Sep-19      39
Oct-19      41

推荐阅读