【发布时间】: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