Donbeo
Donbeo

Reputation: 17617

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?

Upvotes: 4

Views: 5999

Answers (1)

jezrael
jezrael

Reputation: 862671

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:

Upvotes: 7

Related Questions