pandas pd.to_datetime只保留时间没有日期 [英] Pandas pd.to_datetime only keep time do not date
本文介绍了 pandas pd.to_datetime只保留时间没有日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框(熊猫),其列表示日期,格式如下:
I have a dataframe(Pandas), with a column representing dates, in the following format:
import pandas as pd
import tushare as ts
data = ts.get_tick_data('600030',date='2019-06-28',src='tt') [['time','price','change','volume','amount']]
print(data.head())
具体地说,我想使用pd.to_datetime将时间列转换为日期时间。
Specifically, I would like to use pd.to_datetime convert the 'time' column to datetime.
代码为:
import pandas as pd
import tushare as ts
data = ts.get_tick_data('600030',date='2019-06-28',src='tt') [['time','price','change','volume','amount']]
data.index=pd.to_datetime(data['time'])
del data['time']
print(data.head())
结果如下:
price change volume amount
time
2019-06-29 09:25:04 23.85 -0.07 6825 16279485
2019-06-29 09:30:02 23.85 0.00 2736 6529832
2019-06-29 09:30:05 23.85 0.00 3964 9459955
2019-06-29 09:30:08 23.85 0.00 665 1585346
2019-06-29 09:30:11 23.87 0.02 348 830136
我只想要具有datetime样式的时间,而不想要日期。
像这样:
I only want the time with the datetime style but do not the date. Like this:
price change volume amount
time
09:25:04 23.85 -0.07 6825 16279485
09:30:02 23.85 0.00 2736 6529832
09:30:05 23.85 0.00 3964 9459955
09:30:08 23.85 0.00 665 1585346
09:30:11 23.87 0.02 348 830136
所以我需要帮助。
推荐答案
尝试一下
df = pd.DataFrame(data={'date':['2019-06-29 09:25:04','2019-06-29 09:30:02'],
'col2':[2,3]})
df['time'] = pd.to_datetime(df['date']).dt.time
如果要将其作为索引,则只需
if you want to make this as index then just do
df.set_index('time',inplace=True)
这篇关于 pandas pd.to_datetime只保留时间没有日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文