【问题标题】:Pandas Resample on Date ColumnsPandas 在日期列上重新采样
【发布时间】:2018-05-22 03:06:28
【问题描述】:

我有一个dataframe,日期为列。我想将每天的值平均到每月的水平。我试过使用 Time Grouper 和 Resample,但它不喜欢列名是字符串,我似乎可以弄清楚如何将列变成 DatetimeIndex 之类的东西。

我的起始数据框:

import pandas as pd

df = pd.DataFrame(data=[[1,2,3,4],[5,6,7,8]],
                  columns=['2013-01-01', '2013-01-02', '2013-02-03', '2013-02-04'], 
                  index=['A', 'B'])

期望的输出:

   2013-01-01  2013-02-01
A         1.5         3.5
B         5.6         7.5

【问题讨论】:

    标签: python python-2.7 pandas


    【解决方案1】:

    先尝试将列名转换为日期:

    df = pd.DataFrame(data=[[1,2,3,4],[5,6,7,8]], columns=pd.to_datetime(['2013-01-01', '2013-01-02', '2013-02-03', '2013-02-04']), index=['A', 'B'])
    

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      首先,使用pd.to_datetime 将列索引转换为日期时间,然后使用Tgroupbypd.Grouper(注意pd.TimeGerouper is deprecated 使用pd.Grouper):

      df.columns = pd.to_datetime(df.columns)
      df.T.groupby(by=pd.Grouper(freq='MS')).mean().T
      

      输出:

         2013-01-01  2013-02-01
      A         1.5         3.5
      B         5.5         7.5
      

      【讨论】:

        【解决方案3】:

        你可以使用pd.PeriodIndex:

        In [145]: df.groupby(pd.PeriodIndex(df.columns, freq='M'), axis=1).mean()
        Out[145]:
           2013-01  2013-02
        A      1.5      3.5
        B      5.5      7.5
        

        【讨论】:

        • @MaxU 同意 :-)
        • 现在,我明白了..你的方法更简洁 :-) 学习新东西 :~) 非常感谢
        【解决方案4】:

        您可以使用resample

        df.columns = pd.to_datetime(df.columns)
        df.T.resample('M').mean().T
        Out[409]: 
           2013-01-31  2013-02-28
        A         1.5         3.5
        B         5.5         7.5
        

        或者groupby一个

        axis=1 
        df.groupby(pd.to_datetime(df.columns).to_period('M'),1).mean()
        Out[412]: 
           2013-01  2013-02
        A      1.5      3.5
        B      5.5      7.5
        

        【讨论】:

          【解决方案5】:
          import pandas as pd
          
          list=df.columns
          df_new = pd.DataFrame()
          
          for i in range(int(0.5*len(list))):
              df_new[list[2*i]] = (df[[list[2*i], list[2*i+1]]].mean(axis=1))
          

          输出

                 2013-01-01  2013-02-03
          A         1.5         3.5
          B         5.5         7.5
          

          我不明白你想要的输出:

          【讨论】:

          • 这是月平均值。
          • 是的,对于 '2013-01-01',平均值为 1.5 ((1+2)/2) 和 5.5 ((5+6)/2),但对于 2013-02-01平均值为 2.5 ((2+3)/2) 和 6.5 ((6+7)/2),您使用 3.5 ((3+4)/2) 和 7.5 ((7+8)/2)。
          • 不是每天。这是每月一次。看看下面的答案,索引是“月”。即 1 月和 2 月 1 月,A 列的平均值为 (1+2)/2 = 1.5。 2 月,A 列的平均值为 (3+4)/2 = 3.5。我相信你会得到剩下的。
          猜你喜欢
          • 2020-09-29
          • 2016-10-20
          • 2021-12-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-14
          • 1970-01-01
          相关资源
          最近更新 更多