import datetime
import pandas as pd
values = [("a", datetime.date(2015,1,1), 30.),
("a", datetime.date(2015,1,2), 25.)]
columns = ["id", "date", "amount"]
df = pd.DataFrame(values, columns=columns)
df_single = df.set_index("date")
df_multi = df.set_index(["id", "date"])
print(df_multi.index)
print(df_single.index)
Problem description
I have a pandasDataFrame containing a datetime.date column. When I set a multilevel index, the date column is converted to a datetime.datetime object, which does not happen when setting a single-level index. I have posted the question on SO , and I understand the answer. Still, I think this is an unexpected behavior.
Expected Output
The expected output is:
print(df_multi.index)
# MultiIndex(levels=[['a'], [2015-01-01, 2015-01-02]],
# labels=[[0, 0], [0, 1]],
# names=['id', 'date'])
Output of pd.show_versions()
Comment From: jreback
see some discussion https://github.com/pandas-dev/pandas/issues/8802
datetime.date are not first class objects and so are generally coerced
Comment From: ldocao
Thanks @jreback ! However, after reading #8802, I don't see comments about Multi-index vs single-Index behavior, am I right ? I'm fine with date being coerced, but I would expect that pandas will do so in single-index too. What do you think ?
Comment From: jreback
@ldocao not sure what you mean. You have to work pretty hard to actually make a datetime.date
stick around. Can you show an example?
Comment From: ldocao
I posted an example in this issue: if you use set_index("date")
(instead of set_index(["id", "date"])
), then the date object is not coerced as datetime.
Sorry, maybe my post wasn't clear enough: my initial intent was to highlight the different coercion strategy of single vs multi index. Do you need more information from me ?
Comment From: jreback
@ldocao you started with an object
dtype; it happens to be datetime.date
objects, but that requires you to coerce it (e.g. with pd.to_datetime
). I wouldn't recommend you use these objects at all and that is the issue. If you insist on using them you have to do a lot of work.