我有一个这样的csv文件:
"time","student","items"
"09:00:00","Tim","apple"
"09:00:05","Jason","orange"
"09:00:10","Emily","grape"
"09:00:15","Ivy","kiwi"
(很多次,间隔是5秒)
我想使用熊猫让时间成为索引,我希望时间看起来像下面的2019-05-09 09:00:00
datetime.datetime(2019, 5, 9, 9, 0)
我只能得到一个简单的
时间
09:00:00
09:00:05
09:00:10
09:00:15
并且无法获取上述类型
import pandas as pd
df0509 = pd.read_csv("0509.csv",index_col="time")
答案 0 :(得分:0)
使用pd.to_datetime()
代码
import pandas as pd
# Read data
data = pd.read_csv("0509.csv")
# Converting to datetime
data['time'] = pd.to_datetime(data['time'])
# Display dataframe
data.head()
输出
time student items
0 2019-05-20 09:00:00 Tim apple
1 2019-05-20 09:00:05 Jason orange
2 2019-05-20 09:00:10 Emily grape
3 2019-05-20 09:00:15 Ivy kiwi
将日期设置为索引
我不建议这样做,因为索引需要唯一。多行很有可能具有相同的日期时间。
# Code
data.set_index('time', inplace=True)
# Output
student items
time
2019-05-20 09:00:00 Tim apple
2019-05-20 09:00:05 Jason orange
2019-05-20 09:00:10 Emily grape
2019-05-20 09:00:15 Ivy kiwi