pandas 如何去除日期、小时和秒的熊猫日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41954938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to strip a pandas datetime of date, hours and seconds
提问by Josh Kidd
How do I remove Date, Hours and Seconds from a pandas datetime, so that I'm left with only the minutes? I have a table of dates in the format:
如何从Pandas日期时间中删除日期、小时和秒,以便我只剩下分钟?我有一个格式的日期表:
Date
2015-04-18 23:33:58
2015-04-19 14:32:08
2015-04-20 18:42:44
2015-04-20 21:41:19
and I want:
而且我要:
Date
33
32
42
41
The code I'm trying to use is:
我尝试使用的代码是:
fiveMin['Date'] = fiveMin['Date'] - pd.Timedelta(fiveMin['Date'], unit='s')
to remove the seconds, however I'm getting the error:
删除秒,但是我收到错误:
Value must be Timedelta, string, integer, float, timedelta or convertible
回答by EdChum
If the dtype is already datetime
you can use dt
accessor to return just the minute attribute:
如果 dtype 已经是datetime
你可以使用dt
访问器只返回分钟属性:
In [43]:
df['Date'].dt.minute
Out[43]:
0 33
1 32
2 42
3 41
Name: Date, dtype: int64
If needed convert using to_datetime
:
如果需要转换使用to_datetime
:
df['Date'] = pd.to_datetime(df['Date'])`
If the dates are strings and are well formed you could just split on :
and extract the second to last split:
如果日期是字符串并且格式正确,您可以拆分:
并提取倒数第二个拆分:
In [46]:
df['Date'].str.split(':').str[-2]
Out[46]:
0 33
1 32
2 42
3 41
Name: Date, dtype: object
This returns a string series however, if you want ints then you can cast to int using astype(int)
:
但是,这将返回一个字符串系列,如果您想要整数,则可以使用astype(int)
以下方法转换为 int :
In [47]:
(df['Date'].str.split(':').str[-2]).astype(int)
Out[47]:
0 33
1 32
2 42
3 41
Name: Date, dtype: int32