熊猫圆整列的确切价值

我的输入数据框;

     A          B       C 
0    0          1       1.3
1    1.2        2       2.25
2    1.5        3       4.42
3    2.7        4       5.12
4    3.9        5       6.24
5    4.55       6       7.25

我想根据数据帧中的阈值舍入C列。但是我没有得到想要的结果。

代码为;

threshold=0.25
df['C']=round(df['C'] - threshold+0.5)

输出为;

     A          B       C 
0    0          1       2
1    1.2        2       2
2    1.5        3       5
3    2.7        4       5
4    3.9        5       6
5    4.55       6       7

所需的输出为;

     A          B       C 
0    0          1       2
1    1.2        2       3
2    1.5        3       5
3    2.7        4       5
4    3.9        5       6
5    4.55       6       8

我遇到了.25值的麻烦。我也想将这些值取整。 ypu可以帮我吗?

wly1zwss 回答:熊猫圆整列的确切价值

numpy.isclosenumpy.modf用于测试.5作为条件,并以numpy.ceilnumpy.round进行numpy.where的四舍五入:

threshold=0.25

s = df['C'] - threshold+0.5
print (s)
0    1.55
1    2.50
2    4.67
3    5.37
4    6.49
5    7.50
Name: C,dtype: float64

m = np.isclose(np.modf(s)[0],0.5)

df['C']=np.where(m,np.ceil(s),np.round(s))
print (df)
      A  B    C
0  0.00  1  2.0
1  1.20  2  3.0
2  1.50  3  5.0
3  2.70  4  5.0
4  3.90  5  6.0
5  4.55  6  8.0
,

您可以使用numpy.floor并添加布尔值(如果1mod(1)的情况下为>= threshold,如果0<则添加布尔值):

threshold = 0.25
df['C'] = np.floor(df['C']) + df['C'].mod(1).ge(threshold)

[出]

      A  B    C
0  0.00  1  2.0
1  1.20  2  3.0
2  1.50  3  5.0
3  2.70  4  5.0
4  3.90  5  6.0
5  4.55  6  8.0
本文链接:https://www.f2er.com/3161650.html

大家都在问