基于舍入条件从数据帧中排除行

2024-06-16 11:11:55 发布

您现在位置:Python中文网/ 问答频道 /正文

当四舍五入到2位小数的列长度等于列长度时,如何从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)

在这种情况下,它应该下降第一行,当圆柱腿2.05它等于2.05对柱翅膀。你知道吗


Tags: importdataframepandasdfdataasonepd
2条回答

使用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

这是我的解决方案,让我知道这是否适合你。你知道吗

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

输出:

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

相关问题 更多 >