要按日期索引pandas数据帧,可以使用set_index()
方法将日期列设置为索引。以下是一个示例代码:
import pandas as pd
# 创建一个包含日期列的数据帧
df = pd.DataFrame({'date': ['2022-01-01', '2022-01-02', '2022-01-03'],
'value': [1, 2, 3]})
# 将日期列转换为日期时间类型
df['date'] = pd.to_datetime(df['date'])
# 将日期列设置为索引
df.set_index('date', inplace=True)
# 输出结果
print(df)
输出结果:
value
date
2022-01-01 1
2022-01-02 2
2022-01-03 3
在示例代码中,首先创建了一个包含日期列的数据帧df
。然后,使用pd.to_datetime()
方法将日期列转换为日期时间类型。最后,使用set_index()
方法将日期列设置为索引。设置索引时,可以使用inplace=True
参数,表示在原始数据帧上进行修改,而不是创建一个新的数据帧。
这样,就可以按日期索引pandas数据帧了。
下一篇:按日期索引删除行