【问题标题】:how to splits columns by date using python如何使用python按日期拆分列
【发布时间】:2020-11-12 13:01:23
【问题描述】:
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 对日期进行分组?

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

【问题讨论】:

  • @jezrael 不,我认为他不需要melt。我认为他想将 df 拆分为问题中提到的多个 df。
  • @MayankPorwal - 是的,这是不关闭的原因;)

标签: python-3.x pandas time-series


【解决方案1】:

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

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

【讨论】:

  • @BHAVESHSADHU 如果它解决了您的解决方案,请不要忘记接受此答案,以便将其关闭。祝你好运:)
【解决方案2】:

一种直接的方法是将日期列设置为索引并隔开所有其他列:

data.set_index('Month', inplace =True)
data_dict = {col: data[col] for col in data.columns}

【讨论】:

    【解决方案3】:

    您必须创建新的 DataFrame:

    data1 = pd.DataFrame()
    data1['Month'] = df['Month']
    data1['ward1'] = df['ward1']
    data1.head()
    

    【讨论】:

      猜你喜欢
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 2019-08-01
      • 2018-08-16
      • 1970-01-01
      • 2010-09-09
      • 2016-08-06
      • 1970-01-01
      相关资源
      最近更新 更多