[英]Exclude rows from pandas DataFrame based on rounding condition
How can I exclude rows from my df where when rounded value to 2 decimals of column Legs is = to wings column value? 当四舍五入到列Legs的小数点后两位等于=展开列值时,如何从df中排除行?
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. 在这种情况下,当将列支脚舍入2.05等于在列Wings上的2.05时,它应该掉落第一行。
Use np.close
. 使用
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.