根据舍入条件从pandas DataFrame中排除行

时间:2019-07-19 19:37:52

标签: python pandas rounding

如何将我的df中排除的行舍入到列Legs的2位小数是=舍入列值时的行?

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)

在这种情况下,当将列支脚的舍入值2.05等于列Wings的2.05时,它应该下降第一行。

2 个答案:

答案 0 :(得分:1)

使用np.close。设置公差

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

或者,将两列显式舍入到所需的精度,

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

会的。


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

答案 1 :(得分:0)

这是我的解决方案,请告诉我这是否适合您。

<html>
...
...
<h1>$String1</h1>
...
...
</html>

原始数据帧的输出:

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

输出:

   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