'Passing list-likes to .loc or [] with any missing labels is no longer supported, see

Viewed 4270

How to fix the error:

KeyError: 'Passing list-likes to .loc or [] with any missing labels 
is no longer supported, see 
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-reindex-listlike'

I just want to get the locations of the dataframe, that are in the index "ix".

here is a reproducable sample:

import pandas as pd
ix = pd.DatetimeIndex(["2019-07-19 08:47:00", "2019-07-19 08:48:00", "2019-07-19 08:49:00", '2019-07-19 13:43:00', '2019-07-19 13:44:00', '2019-07-19 13:45:00', '2019-07-19 13:46:00', '2019-07-19 13:47:00', '2019-07-19 13:48:00', '2019-07-19 13:49:00', '2019-07-19 13:50:00', '2019-07-19 13:51:00', '2019-07-19 13:52:00'], dtype='datetime64[ns]', name='Time', freq=None)
df = pd.DataFrame({"result":[7.445043,0.585584,1.735565,3.217186, 0.211871,0.000000,0.180448,21.645403,22.724170,304.292450]}, index = [
"2019-07-19 08:47:00", "2019-07-19 08:48:00", "2019-07-19 08:49:00", "2019-07-19 08:50:00", "2019-07-19 08:51:00", "2019-07-19 08:52:00",  "2019-07-19 08:53:00", "2019-07-19 08:54:00",   "2019-07-19 08:55:00",  "2019-07-19 08:56:00"   ])
df.index = pd.to_datetime(df.index)

result = df.loc[ix]
print(result)
2 Answers

You might try something like this:

result = df.loc[df.index.intersection(ix)]

For searching a dataframe index, you can just use a standard list with df.index.isin.

Try this code:

import pandas as pd
from datetime import datetime

# string dates
dtsearch = ["2019-07-19 08:47:00", "2019-07-19 08:48:00", "2019-07-19 08:49:00", '2019-07-19 13:43:00', 
            '2019-07-19 13:44:00', '2019-07-19 13:45:00', '2019-07-19 13:46:00', '2019-07-19 13:47:00', 
            '2019-07-19 13:48:00', '2019-07-19 13:49:00', '2019-07-19 13:50:00', '2019-07-19 13:51:00', 
            '2019-07-19 13:52:00']

# convert to datetime
dts = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in dtsearch]

# build dataframe
df = pd.DataFrame({"result":[7.445043,0.585584,1.735565,3.217186, 0.211871,0.000000,0.180448,21.645403,
                              22.724170,304.292450]}, 
     index = ["2019-07-19 08:47:00", "2019-07-19 08:48:00", "2019-07-19 08:49:00", "2019-07-19 08:50:00", 
              "2019-07-19 08:51:00", "2019-07-19 08:52:00",  "2019-07-19 08:53:00", "2019-07-19 08:54:00",   
              "2019-07-19 08:55:00", "2019-07-19 08:56:00"])

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

# search index using date list
df2 = df[df.index.isin(dts)]

print(df2)

Output

                       result
2019-07-19 08:47:00  7.445043
2019-07-19 08:48:00  0.585584
2019-07-19 08:49:00  1.735565
Related