Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas most efficient way to compare dataframe and series

I have a dataframe of shape (n, p) and a series of length n

I can compare them with:

for i in df.keys(): df[i] > ts

Is there a way to do it in one line? something like df > ts. if yes, is it more efficient?

like image 440
Donbeo Avatar asked Oct 29 '25 01:10

Donbeo


1 Answers

I think you need DataFrame.gt:

print (df.gt(s, axis=0))

Sample:

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df)
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

s = pd.Series([1,2,3])
print (s)
0    1
1    2
2    3
dtype: int64

print (df.gt(s, axis=0))
       A     B     C      D     E      F
0  False  True  True  False  True   True
1  False  True  True   True  True   True
2  False  True  True   True  True  False

If need another functions for compare:

  • lt
  • gt
  • le
  • ge
  • ne
  • eq
like image 186
jezrael Avatar answered Oct 31 '25 22:10

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!