Pandas如何缩短分、秒pandas.tslib.Timestamp

2024-06-08 03:13:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用clouderavm5.2和pandas 0.18.0。在

我有以下数据

adclicksDF = pd.read_csv('/home/cloudera/Eglence/ad-clicks.csv',
               parse_dates=['timestamp'],
       skipinitialspace=True).assign(adCount=1)

adclicksDF.head(n=5)
Out[107]: 
            timestamp  txId  userSessionId  teamId  userId  adId   adCategory  \
0 2016-05-26 15:13:22  5974           5809      27     611     2  electronics   
1 2016-05-26 15:17:24  5976           5705      18    1874    21       movies   
2 2016-05-26 15:22:52  5978           5791      53    2139    25    computers   
3 2016-05-26 15:22:57  5973           5756      63     212    10      fashion   
4 2016-05-26 15:22:58  5980           5920       9    1027    20     clothing   



   adCount  
0        1  
1        1  
2        1  
3        1  
4        1  

数据类型字段是

^{pr2}$

我想截短时间戳中的分钟和秒。在

我试过了

adclicksDF["timestamp"] = pd.to_datetime(adclicksDF["timestamp"],format='%Y-%m-%d %H')

adclicksDF.head(n=5)
Out[110]: 
            timestamp  txId  userSessionId  teamId  userId  adId   adCategory  \
0 2016-05-26 15:13:22  5974           5809      27     611     2  electronics   
1 2016-05-26 15:17:24  5976           5705      18    1874    21       movies   
2 2016-05-26 15:22:52  5978           5791      53    2139    25    computers   
3 2016-05-26 15:22:57  5973           5756      63     212    10      fashion   
4 2016-05-26 15:22:58  5980           5920       9    1027    20     clothing   

   adCount  
0        1  
1        1  
2        1  
3        1  
4        1  

这不会缩短分钟和秒。在

我怎样才能缩短分钟和秒?在


Tags: csvmoviesoutheadtimestamppduseridelectronics
3条回答

尝试:

pd.to_datetime(adclicksDF.timestamp).dt.strftime('%Y-%m-%d %H')

分配后:

^{pr2}$

enter image description here

您可以使用:

adclicksDF["timestamp"] = pd.to_datetime(adclicksDF["timestamp"])
                            .apply(lambda x: x.replace(minute=0, second=0))


print (adclicksDF)
            timestamp  txId  userSessionId  teamId  userId  adId   adCategory
0 2016-05-26 15:00:00  5974           5809      27     611     2  electronics
1 2016-05-26 15:00:00  5976           5705      18    1874    21       movies
2 2016-05-26 15:00:00  5978           5791      53    2139    25    computers
3 2016-05-26 15:00:00  5973           5756      63     212    10      fashion
4 2016-05-26 15:00:00  5980           5920       9    1027    20     clothing

print (type(adclicksDF.ix[0, 'timestamp']))
<class 'pandas.tslib.Timestamp'>

如果需要输出为string,请使用^{}

^{pr2}$

编辑:

更好的解决方案是用dt.floor来回答Alex

pd.Timestamp自0.18起有一个floor分辨率方法

adclicksDF["timestamp"] = adclicksDF.timestamp.dt.floor('h')

相关问题 更多 >

    热门问题