Python 使用pandas从csv中提取小时数
我有一个csv,看起来像这样Python 使用pandas从csv中提取小时数,python,time,pandas,Python,Time,Pandas,我有一个csv,看起来像这样 time,result 1308959819,1 1379259923,2 1318632821,3 1375216682,2 1335930758,4 时间是unix格式的。我想根据这些值从这些时间和文件中提取小时数 我试过了 times = pd.to_datetime(df.time, unit='s') 甚至 times = pd.DataFrame(pd.to_datetime(df.time, unit='s')) 但在这两种情况下,我都犯了一个错
time,result
1308959819,1
1379259923,2
1318632821,3
1375216682,2
1335930758,4
时间是unix格式的。我想根据这些值从这些时间和文件中提取小时数
我试过了
times = pd.to_datetime(df.time, unit='s')
甚至
times = pd.DataFrame(pd.to_datetime(df.time, unit='s'))
但在这两种情况下,我都犯了一个错误
times.hour
>>>AttributeError: 'DataFrame' object has no attribute 'hour'
您可以使用内置类来实现这一点
import datetime
# your code here
hours = datetime.datetime.fromtimestamp(df.time).hour
之所以出现此错误,是因为序列和数据帧没有
hour
属性。您可以使用.dt
便利访问器(docs)访问所需信息:
>>times=pd.to_datetime(df.time,unit='s')
>>>时代
0 2011-06-24 23:56:59
1 2013-09-15 15:45:23
2 2011-10-14 22:53:41
3 2013-07-30 20:38:02
4 2012-05-02 03:52:38
名称:时间,数据类型:datetime64[ns]
>>>泰晤士报
>>>时间.dt.hour
0 23
1 15
2 22
3 20
4 3
数据类型:int64
>>> times = pd.to_datetime(df.time, unit='s')
>>> times
0 2011-06-24 23:56:59
1 2013-09-15 15:45:23
2 2011-10-14 22:53:41
3 2013-07-30 20:38:02
4 2012-05-02 03:52:38
Name: time, dtype: datetime64[ns]
>>> times.dt
<pandas.tseries.common.DatetimeProperties object at 0xb5de94c>
>>> times.dt.hour
0 23
1 15
2 22
3 20
4 3
dtype: int64