【问题标题】:How to round date time index in a pandas data frame?如何在熊猫数据框中舍入日期时间索引?
【发布时间】:2019-02-11 13:27:50
【问题描述】:

有一个这样的熊猫数据框:

index
2018-06-01 02:50:00     R 45.48 -2.8 
2018-06-01 07:13:00     R 45.85 -2.0  
... 
2018-06-01 08:37:00     R 45.87  -2.7

我想像这样将索引四舍五入到小时:

index
2018-06-01 02:00:00     R 45.48 -2.8 
2018-06-01 07:00:00     R 45.85 -2.0  
... 
2018-06-01 08:00:00     R 45.87  -2.7

我正在尝试以下代码:

df = df.date_time.apply ( lambda x : x.round('H'))

但返回一个系列而不是带有修改索引列的数据框

【问题讨论】:

    标签: python pandas datetime dataframe


    【解决方案1】:

    试试我的方法:

    按小时的舍入值添加一个新列:

    df['E'] = df.index.round('H')

    设置为索引:

    df1 = df.set_index('E')

    删除你设置的名字(这里是'E'):

    df1.index.name = None

    现在,df1 是一个新的 DataFrame,索引小时从 df 四舍五入。

    【讨论】:

      【解决方案2】:

      尝试使用floor

      df.index.floor('H')
      

      设置:

      df = pd.DataFrame(np.arange(25),index=pd.date_range('2018-01-01 01:12:50','2018-01-02 01:12:50',freq='H'),columns=['Value'])
      df.head()
                          Value
      2018-01-01 01:12:50 0
      2018-01-01 02:12:50 1
      2018-01-01 03:12:50 2
      2018-01-01 04:12:50 3
      2018-01-01 05:12:50 4
      
      df.index = df.index.floor('H')
      df.head()
                          Value
      2018-01-01 01:00:00 0
      2018-01-01 02:00:00 1
      2018-01-01 03:00:00 2
      2018-01-01 04:00:00 3
      2018-01-01 05:00:00 4
      

      【讨论】:

        【解决方案3】:

        试试这个

        df['index'].apply(lambda dt: datetime.datetime(dt.year, dt.month, dt.day, dt.hour,60*(dt.minute // 60)))
        

        【讨论】:

          猜你喜欢
          • 2021-05-03
          • 2020-01-05
          • 2021-03-19
          • 2017-02-08
          • 1970-01-01
          • 1970-01-01
          • 2021-03-27
          • 2021-04-08
          • 2021-03-12
          相关资源
          最近更新 更多