Select rows by indices - Pandas loc - any missing labels

801 Views Asked by At

Python version 3.8.5 / Pandas version 1.1.2

To display the rows of the indices from 0 to 99, I used

df[df.col_1 > 60].loc[range(0,99), 'col_2']

But I've got this error message

KeyError: "Passing list-likes to .loc or [] with any missing labels is no longer supported. The following labels were missing: Int64Index([ 1, 3, 4, 6, 7,\n ...\n 95, 96, 97, 98, 99],\n dtype='int64', length=72). See https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-reindex-listlike"

For an alternative, I have this option which is working for my case:

df[df.col_1 > 2].loc[0:4, 'col_2']

I heard that it's no longer accepted for the new pandas version. Thanks for any confirmation.

3

There are 3 best solutions below

0
On

I think here is better chain 2 masks by & and pass to one loc:

df[(df.col_1 > 60) & df.index.isin(range(99)), 'col_2']
0
On

beacause of the filter df.col1>60 some of the indices are not present in the dataframe but u gave an argument of range(0,99) in loc so as they are not present it raised an error. if u want 100 elements. use this

df[df.col_1 > 60].iloc[range(0,99), 'col_2']

if u want with in 1st hundred elements try this:

df=df.loc[range(99), ["col_1",'col_2']]
df[df[loc_1]>60].drop("col_1",axis=1)
0
On

Try in the below way.

Here instead of considering all values of range(99), we are taking intersection.

df[df.col_1 > 60].loc[df[df.col_1 > 60].index.intersection(range(99)), 'col_2']