【问题标题】:read excel and convert index to datatimeindex pandas读取 excel 并将索引转换为 datetimeindex 熊猫
【发布时间】:2016-10-21 10:50:39
【问题描述】:

我读过这样的熊猫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
...

我想把索引转成datatimeindex,我试过了

df.index = pd.to_datetime(df.index)

得到:“ValueError: Unknown string format”

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

【问题讨论】:

    标签: python excel pandas


    【解决方案1】:

    我认为您需要添加参数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
    

    【讨论】:

    • 我也试过了,但得到:“ValueError:未转换的数据仍然存在:b”???
    • 您的数据似乎不正确-您可以检查所有无法通过print (df[pd.to_datetime(df.index, format='%d.%m.%Y %H:%M:%S', errors='coerce').to_series().isnull().values]) 转换为日期时间索引的行。什么回报呢?
    • Thgen 你可以用NaT 替换所有错误值df.index = pd.to_datetime(df.index, format='%d.%m.%Y %H:%M:%S', errors='coerce')
    • 好吧,你是对的,坏数据,没有意识到这一点。我删除了那些数据,现在它可以工作了。
    • 非常感谢您的帮助!
    猜你喜欢
    • 2021-01-22
    • 2013-02-18
    • 2019-09-28
    • 2021-11-11
    • 2022-12-04
    • 2021-03-01
    • 2019-03-26
    • 2021-08-28
    • 1970-01-01
    相关资源
    最近更新 更多