python - 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 列作为索引并删除另一列?
解决方案
读完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
"""
推荐阅读
- javascript - 在 JavaScript 中更新对象属性的更短方法?
- xamarin.forms - 如何在 xamarin 表单中更改搜索栏搜索图标的颜色和取消按钮颜色
- ruby-on-rails - Rails RSS Feed 未呈现为 XML
- python - Pyspark Luigi 多个工人问题
- python - 检测数据框中的特定字符
- python - Binance 期货测试网上的空头订单导致 APIError(ReduceOnly 订单被拒绝)
- python - 无法单击 xpath 选定对象 Selenium (Python)
- swiftui - 如何影响 SwiftUI contextMenu 展示位置?
- c++ - 如何在 c++ 中为 QSortFilterProxyModel 定义函数“过滤器”?
- vba - excel VBA中的错误“ODBC驱动程序不支持请求的属性”