0

How can I exclude rows from my df where when rounded value to 2 decimals of column Legs is = to wings column value?

import pandas as pd
d = {'legs': [2.051, 4.07, 8.298, 0.234],'wings': [2.05, 4.179,8.903,0.294],'seen': ['five', 'one', 'two', 'four']}
df = pd.DataFrame(data=d)

print(df)

in this case, it should drop first row ,when rounding column legs 2.05 its equal to 2.05 on column Wings.

cs95
  • 379,657
  • 97
  • 704
  • 746
Paxsivir
  • 99
  • 1
  • 1
  • 4

2 Answers2

1

Use np.close. Either setting the tolerance,

pd.np.isclose(df.legs, df.wings, atol=1e-2)                                                        
# array([ True, False, False, False])

Or, explicitly rounding both columns to the desired precision,

pd.np.isclose(df.legs.round(2), df.wings)                                                 
# array([ True, False, False, False])

Will do.


df[~pd.np.isclose(df.legs.round(2), df.wings)]                                          

    legs  seen  wings
1  4.070   one  4.179
2  8.298   two  8.903
3  0.234  four  0.294
cs95
  • 379,657
  • 97
  • 704
  • 746
  • Is it possible to do it just Rounding legs and checking if its equal to wings value? and not rounding wings aswell? – Paxsivir Jul 19 '19 at 19:47
  • @Paxsivir My obvious first choice would be to remove .round() from wings and just do: `df[~pd.np.isclose(df.legs.round(2), df.wings)] ` – cs95 Jul 19 '19 at 19:48
0

Here is my solution, let me know if this works for you.

d = {'legs': [2.051, 4.07, 8.298, 0.234],'wings': [2.05, 4.179,8.903,0.294],'seen': ['five', 'one', 'two', 'four']} #dictionary
df = pd.DataFrame(data=d).round(2)#creating the dataframe and also rounding it to 2 decimal

output of the original data frame:

   legs    wings    seen
0   2.05    2.05    five
1   4.07    4.18    one
2   8.30    8.90    two
3   0.23    0.29    four

df_new = df[df['legs'] != df['wings']] #this will apply the condition and assign it to new dataframe or anything else.
df_new

output:

    legs    wings   seen
1   4.07    4.18    one
2   8.30    8.90    two
3   0.23    0.29    four
Vishwas
  • 343
  • 2
  • 13
  • 1
    Never use equality for floating point comparisons. See [Is floating point arithmetic broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – cs95 Jul 20 '19 at 01:02