-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Slicing Datetime MultiIndex with string or datetime.date slices #15906
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
and strings work fine.
|
all that said, if you want to do a PR to support indexing via |
We actually do support it:
Above is on normal DatetimeIndex (the key is just coerced to a Timestamp). MultiIndex has always lagged somewhat behind on that. Not that I recommend using a datetime.date! |
reopening as doesn't work on MI as indicated above. |
I see this issue is still open. I have a similar problem on pandas 1.1.1: df = pd.DataFrame({'a': ['2020-01-01', '2020-02-01', '2020-03-01'], 'b': [1, 2, 3], 'c': [10, 20, 30]})
df['a'] = pd.to_datetime(df['a'])
df = df.set_index(['a', 'b'])
df.loc[('2020-01-01', 1)] # This works.
df.loc[[('2020-01-01', 1), ('2020-02-01', 2)]] # This fails.
df.loc[[(pd.Timestamp(2020, 1, 1), 1), (pd.Timestamp(2020, 2, 1), 2)]] # This works. So, if you have a multiindex dataframe with a datetime index, you can access the datetime index as a string only if you extract one row. If you try to extract more than one, dates have to be given as timestamps. I know this is not a very common scenario, but is there any plan to solve it, or is there any workaround? Thank you! |
Just to build on what @pabloarosado has commented, by using datetime.datetime or datetime.date the multindex slicing also seems to work: df.loc[[(datetime.datetime(2020, 1, 1), 1), (datetime.datetime(2020, 2, 1), 2)]] # This works
df.loc[[(datetime.date(2020, 1, 1), 1), (datetime.date(2020, 2, 1), 2)]] # This also works |
Basically Indexing a MultiIndex with a DatetimeIndex seems only to be working if you use slices with
datetime.datetime
orpandas.Timestamp
. One would expect it to work also with strings as well as with 'datetime.date' slices as it does for usual indizes.This seems to be related to #3843.
Code Sample, a copy-pastable example if possible
Problem description
The above code raises the following exception on the last line, which is quite unexpected when one is used to indexing on single index dataframes.
Output of
pd.show_versions()
The text was updated successfully, but these errors were encountered: