python - 读取 excel 并将索引转换为 datetimeindex Pandas

标签 python excel pandas

我读过这样的 Pandas excel

df = pd.read_excel("Test.xlsx", index_col=[0])

数据框看起来像这样,索引包含日期和时间以及一列:
01.01.2015 00:15:00     47.2
01.01.2015 00:30:00     46.6
01.01.2015 00:45:00     19.4
01.01.2015 01:00:00     14.8
01.01.2015 01:15:00     14.8
01.01.2015 01:30:00     16.4
01.01.2015 01:45:00     16.2
...

我想将索引转换为数据时间索引,我试过了
df.index = pd.to_datetime(df.index)

并得到:“ValueError:未知的字符串格式”

将索引转换为包含日期和时间的数据时间格式以使用基于日期时间的函数的最佳方法是什么

最佳答案

我认为您需要添加参数format - 见 http://strftime.org/ :

df.index = pd.to_datetime(df.index, format='%d.%m.%Y %H:%M:%S')

print (df)
                        a
2015-01-01 00:15:00  47.2
2015-01-01 00:30:00  46.6
2015-01-01 00:45:00  19.4
2015-01-01 01:00:00  14.8
2015-01-01 01:15:00  14.8
2015-01-01 01:30:00  16.4
2015-01-01 01:45:00  16.2

关于python - 读取 excel 并将索引转换为 datetimeindex Pandas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40174721/

相关文章:

python - 如何解决列 res_partner.<column> 在 Odoo 中不存在?

python - Pandas Left Merge 与 xlsx 和 CSV 在输出中生成空值列

python - 无法将表写入 Pandas DataFrame

python - pandas.read_excel 的类型错误

python - 将月末或周末系列转换为每日系列

python - 使用 python3 访问 Google Sheets 上的电子表格

python - Kivy 文本标记打印自己的语法

python - 在 Python 中从一个文件读取和写入一个新行到另一个文件

excel - VBA - 列出给定文件夹及其所有子文件夹中的给定扩展名的文件名,直到最后一级

excel - 从另一个工作表的单元格列替换第一行中的标题名称