NCFY
NCFY

Reputation: 79

.loc on multiple columns with the same condition

I am trying to select rows using .loc with a single condition that multiple columns have to meet:

# %%
a = (100, 50, 75, 100, 100, 50)
b = (100, 25, 15, 100, 75, 50)
c = (100, 75, 50, 100, 100, 25)

df = pd.DataFrame(zip(a, b, c), columns = ['A' , 'B' , 'C'])

col_lst = ('A' , 'B' , 'C')

Those two lines "should" produce the same output:

df.loc[df[col_lst] == 100]
    Out: 
ValueError: Cannot index with multidimensional key

df.loc[(df['A'] == 100) & (df['B'] == 100) & (df['C'] == 100)]
    Out:
    A   B   C
0   100 100 100
3   100 100 100

Is it not possible to use .loc with a list of labels?

Upvotes: 4

Views: 2055

Answers (1)

anky
anky

Reputation: 75080

You need to convert the tuple into list and combine with all in axis=1:

df[(df[list(col_lst)] == 100).all(1)]
#df.loc[(df[list(col_lst)] == 100).all(1)]

Upvotes: 3

Related Questions