我希望将一行值的总和四舍五入到最接近的偶数,除非该值在0.75和3之间,则该值应四舍五入为2。
数据
Location range type Q1 24 Q2 24 Q3 24 Q4 24
NY low SS 0 0.79 0 0
NY low SS 0 0 0 0
CA low AA 0.24 0.34 0.93 1.07
CA low AA 1.71 0.57 0 0
CA low BB 0.08 0.11 0.65 0.47
CA low BB 0 0 2 0
CA low DD 0.35 0.5 1.37 1.57
期望
Location range type Q1 24 Q2 24 Q3 24 Q4 24 rounded_sum
NY low SS 0 0.79 0 0 2
NY low SS 0 0 0 0 0
CA low AA 0.24 0.34 0.93 1.07 2
CA low AA 1.71 0.57 0 0 2
CA low BB 0.08 0.11 0.65 0.47 2
CA low BB 0 0 2 0 2
CA low DD 0.35 0.5 1.37 1.57 4
做
SO成员有帮助,但如果总和大于或等于0.75,则需要调整,它应该四舍五入到值2。
# using np.where, check if integer part is even or odd
# if odd, add 1 else, keep the integer as is
df2['rounded_sum']=np.where(df2['rounded_sum'].astype(int)%2==1,
df2['rounded_sum'].astype(int) +1,
df2['rounded_sum'].astype(int))
任何建议都很感激
4条答案
按热度按时间woobm2wo1#
似乎你可以定义一个函数来舍入你的数字
然后形成一个新的数组,并用Q1、Q2、Q3和Q4的和填充它:
然后你可以用“map”和我们的函数修改你的数组,并把它写到你的dataframe中:
或者将其替换为lambda:
但我认为没有lambda的代码看起来更好)
P.S.对不起我的英语
xlpyo6sf2#
在
np.where
中使用round
:xu3bshqb3#
让我们试试
np.where
:注意
.between(0.75, 2)
和.between(0.75,3)
由于round()
操作而给予相同的结果。ki0zmccv4#
试试看