safex
safex

Reputation: 2514

Pandas compare multiple columns against one column

I want to compare many columns in a dataframe against one column. Is there a non-loop way of doing this?

df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9], 'd':[5,7,2]})
# works but requires one line per column
df['a'] = df['a'] < df['d']
df['b'] = df['b'] < df['d']
df['c'] = df['c'] < df['d']

# df[['a','b','c']] =  df[['a','b','c']] <  df[['d']]

Upvotes: 2

Views: 212

Answers (1)

jezrael
jezrael

Reputation: 863531

Use DataFrame.lt with axis=0 method, remove one [] from select d for select by Series:

df[['a','b','c']] =  df[['a','b','c']].lt(df['d'], axis=0)
print (df)
       a      b      c  d
0   True   True  False  5
1   True   True  False  7
2  False  False  False  2

Or you can compare by numpy array created from column d:

df[['a','b','c']] =  df[['a','b','c']] < df['d'].to_numpy()
print (df)
      a     b      c  d
0  True  True  False  5
1  True  True  False  7
2  True  True  False  2

Upvotes: 3

Related Questions