从 Pandas 数据框列中删除“秒"和“分钟" [英] Remove 'seconds' and 'minutes' from a Pandas dataframe column

查看:63
本文介绍了从 Pandas 数据框列中删除“秒"和“分钟"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个如下的数据框:

Given a dataframe like:

import numpy as np
import pandas as pd

df = pd.DataFrame(
{'Date' : pd.date_range('1/1/2011', periods=5, freq='3675S'),
 'Num' : np.random.rand(5)})
                 Date       Num
0 2011-01-01 00:00:00  0.580997
1 2011-01-01 01:01:15  0.407332
2 2011-01-01 02:02:30  0.786035
3 2011-01-01 03:03:45  0.821792
4 2011-01-01 04:05:00  0.807869

我想删除分钟"和秒"信息.

I would like to remove the 'minutes' and 'seconds' information.

以下内容(大部分来自:如何删除Pandas 数据帧索引的秒"?)工作正常,

The following (mostly stolen from: How to remove the 'seconds' of Pandas dataframe index?) works okay,

df = df.assign(Date = lambda x: pd.to_datetime(x['Date'].dt.strftime('%Y-%m-%d %H')))
                 Date       Num
0 2011-01-01 00:00:00  0.580997
1 2011-01-01 01:00:00  0.407332
2 2011-01-01 02:00:00  0.786035
3 2011-01-01 03:00:00  0.821792
4 2011-01-01 04:00:00  0.807869

但是将日期时间转换为字符串然后再转换回日期时间感觉很奇怪.有没有办法更直接地做到这一点?

but it feels strange to convert a datetime to a string then back to a datetime. Is there a way to do this more directly?

推荐答案

dt.round

这应该是怎么做的...使用 dt.round

df.assign(Date=df.Date.dt.round('H'))

                 Date       Num
0 2011-01-01 00:00:00  0.577957
1 2011-01-01 01:00:00  0.995748
2 2011-01-01 02:00:00  0.864013
3 2011-01-01 03:00:00  0.468762
4 2011-01-01 04:00:00  0.866827

老答案

一种方法是设置索引并使用 resample

One approach is to set the index and use resample

df.set_index('Date').resample('H').last().reset_index()

                 Date       Num
0 2011-01-01 00:00:00  0.577957
1 2011-01-01 01:00:00  0.995748
2 2011-01-01 02:00:00  0.864013
3 2011-01-01 03:00:00  0.468762
4 2011-01-01 04:00:00  0.866827

另一种方法是去掉 datehour 组件

Another alternative is to strip the date and hour components

df.assign(
    Date=pd.to_datetime(df.Date.dt.date) +
         pd.to_timedelta(df.Date.dt.hour, unit='H'))

                 Date       Num
0 2011-01-01 00:00:00  0.577957
1 2011-01-01 01:00:00  0.995748
2 2011-01-01 02:00:00  0.864013
3 2011-01-01 03:00:00  0.468762
4 2011-01-01 04:00:00  0.866827

这篇关于从 Pandas 数据框列中删除“秒"和“分钟"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆