Pandas - Compare Positive/negative Values
I have a dataframe 'df': x y 0 1 -1 1 -2 -3 2 3 4 3 4 5 4 9 6 I am trying to determine what percentage of x and y values are in agreement in terms of being p
Solution 1:
If we compare a product of x*y >= 0
- this should give us "good"
rows:
In [19]: df['x'].mul(df['y']).ge(0)
Out[19]:
0 False
1 True
2 True
3 True
4 True
dtype: bool
In [20]: df.loc[df['x'].mul(df['y']).ge(0)]
Out[20]:
x y
1 -2 -3234345496
In [21]: len(df.loc[df['x'].mul(df['y']).ge(0)])/len(df)
Out[21]: 0.8
or as proposed by @NickilMaveli a faster and more "Pandaic" version:
In [23]: df['x'].mul(df['y']).ge(0).mean()
Out[23]: 0.80000000000000004
the same idea, but this time using df.eval() method:
In [27]: df.eval('x * y >= 0').mean()
Out[27]: 0.80000000000000004
Post a Comment for "Pandas - Compare Positive/negative Values"