首页 > 解决方案 > Python:读取excel文件但索引应该是日期时间而不是序号

问题描述

嘿,我正在从 Excel 工作表中加载数据。excel表格有5列。第一个列是日期时间,接下来的 4 个是与该时间对应的数据集。这是代码:

import os
import numpy as np
import pandas as pd


df = pd.read_excel (r'path\test.xlsx', sheet_name='2018')

我认为它会以 DateTime 为索引的方式加载它,但它有另一个名为 Index 的列,它只是一组从 0 到数组末尾的数字。如何将 DateTime 列作为索引并删除另一列?

标签: pythonanaconda

解决方案


读完excel后试试这个,多了两行

df['Datetime'] = pd.to_datetime(df['Datetime'], format="%m/%d/%Y, %H:%M:%S") 
"""
Assuming that Datetime is the name of the Datetime column and the format of the column is  07/15/2020 12:24:45 -"%m/%d/%Y, %H:%M:%S"
if the format of the date time string is different change the format mentioned 
"""
df = df.set_index(pd.DatetimeIndex(df['Datetime'])) 
"""
This will set the index as datetime index
"""


推荐阅读