【问题标题】:Pandas Multiindex not working with read_csv and datetime objectsPandas Multiindex 不适用于 read_csv 和 datetime 对象
【发布时间】:2014-09-23 09:53:42
【问题描述】:

当我有一个包含多个日期的多索引时,从 csv 加载数据帧时出现问题。

我正在运行以下代码:

import pandas as pd
import datetime
date1 = datetime.date.today()
date2 = datetime.date.today().replace(month=1)
date_cols=['date1', 'date2']
index = pd.MultiIndex.from_product([[date1],[date2]])

#create dataframe with a single row
df= pd.DataFrame([{'date1':date1, 'date2':date2, 'a':1, 'b':2}])
df.set_index(date_cols, inplace=True)
#print the single row -> correct
print df.loc[index]

# write to csv and load it again
df.to_csv('df.csv')
dfr = pd.read_csv('df.csv', parse_dates=date_cols, dayfirst=True)
dfr.set_index(date_cols, inplace=True)
# print the single row -> incorrect, shows nan,
print dfr.loc[index]

虽然我希望得到相同的输出,即数据框中的单行, 第二个打印语句打印出 nan,因为索引不在数据框中。 运行 df.index 时,我看到 multiindex 对象包含两个日期,但现在还包含时间信息,其中时间为 00:00:00

这是一个错误吗?

【问题讨论】:

    标签: python datetime pandas multi-index


    【解决方案1】:

    你所做的事情略有不同。

    In [31]: df.index.levels[0]
    Out[31]: Index([2014-07-31], dtype='object')
    
    In [32]: dfr.index.levels[0]
    Out[32]: 
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2014-07-31]
    Length: 1, Freq: None, Timezone: None
    

    初始创建(使用MultiIndex.from_product 正在使用datetimes。在多索引创建中,我想这可能会导致自动创建DatetimeIndex,而不是datetimes 的普通Index

    当在正确的DatetimeIndex 中读回它时,会创建。我会打开一个问题来思考这个问题。见here

    【讨论】:

    • 当我将 date1 和 date2 初始化为 pandas.datetime 对象而不是 datetime.datetime 对象时,它工作正常。顺便说一句,感谢您的快速响应
    • 是的,它们就是Timestamps(它与datetimes等价但不完全相同)
    猜你喜欢
    • 2021-04-18
    • 1970-01-01
    • 2018-07-13
    • 2016-09-14
    • 1970-01-01
    • 2012-06-03
    • 2014-05-13
    • 2020-08-01
    • 1970-01-01
    相关资源
    最近更新 更多