将数字舍入至最接近的偶数。

huangapple go评论77阅读模式
英文:

Rounding down numbers to the nearest even number

问题

我有一个包含数字列的数据框,看起来像这样:

data = [291.79, 499.31, 810.93, 1164.25]
df = pd.DataFrame(data, columns=['Onset'])

有一种优雅的方法可以将奇数向下舍入到最近的偶数吗?偶数应该四舍五入到最近的偶数。这应该是输出:

data = [290, 498, 810, 1164]
df = pd.DataFrame(data, columns=['Onset'])

谢谢!

英文:

I have a dataframe with a column of numbers that look like this:

data = [291.79, 499.31, 810.93, 1164.25]
df = pd.DataFrame(data, columns=['Onset'])

Is there an elegant way to round down the odd numbers to the nearest even number? The even numbers should be rounded to the nearest even integer. This should be the output:

data = [290, 498, 810, 1164]
df = pd.DataFrame(data, columns=['Onset'])

Thank you!

答案1

得分: 2

当然!有很多方法。一种方法是将一个数字减半,然后使用地板除法,然后再将其加倍。这可以按传统方式完成:

def round_down_even(n):
    return 2 * int(n // 2) 

然后只需使用

df["Onset"] = df["Onset"].apply(round_down_even)

或者如mozway指出的,更有效率的方法是

df['Onset'] = df['Onset'].floordiv(2).mul(2)

(大约快20%,而且更简洁)

英文:

Sure! Plenty of ways. One way could be halving a number, then using floor division, and then doubling it. This can be done in the traditional way:

def round_down_even(n):
    return 2 * int(n // 2) 

Then just use

df["Onset"] = df["Onset"].apply(round_down_even)

or as mozway points out, a more efficient way is

df['Onset'] = df['Onset'].floordiv(2).mul(2)

(Approx 20% faster, as well as more clean)

答案2

得分: 2

我会使用模运算符

```py
df['Onset_new'] = (i:=df['Onset'].astype(int)) - i % 2
print(df)

打印结果:

     Onset  Onset_new
0   291.79        290
1   499.31        498
2   810.93        810
3  1164.25       1164

<details>
<summary>英文:</summary>

I&#39;d use modulo operator:

```py
df[&#39;Onset_new&#39;] = (i:=df[&#39;Onset&#39;].astype(int)) - i % 2
print(df)

Prints:

     Onset  Onset_new
0   291.79        290
1   499.31        498
2   810.93        810
3  1164.25       1164

答案3

得分: 2

df.apply(lambda x:np.floor(x)-np.floor(x)%2)
英文:
df.apply(lambda x:np.floor(x)-np.floor(x)%2)

答案4

得分: 1

有一种简洁的方法(一行代码)可以使用流行的numpy库来实现这一点。您可以利用numpy.floornumpy.ceil函数分别向下和向上取整。

要对数据进行四舍五入,可以使用如下代码(使用类似整数除法的技术):

rounded_data = np.where(np.mod(np.floor(data), 2) == 1, np.floor(data) // 2 * 2, np.ceil(data) // 2 * 2)

请记住,import numpy as np这一行是必要的。

在将数据框DataFrame的数据四舍五入后,rounded_data的输出如下:

dfRounded = pd.DataFrame(rounded_data, columns=[&#39;Onset&#39;])
print(dfRounded)

结果为:

    Onset
0   290.0
1   498.0
2   810.0
3  1164.0

最后,如果您想将值转换为整数,可以使用:

dfRounded[&#39;Onset&#39;] = dfRounded[&#39;Onset&#39;].astype(int)
英文:

There is an elegant way (one-liner) to achieve this using the popular numpy library. You can make use of the numpy.floor and numpy.ceil functions to round down and up, respectively.
The code to round the data would be (using techniques like integer division):

rounded_data = np.where(np.mod(np.floor(data), 2) == 1, np.floor(data) // 2 * 2, np.ceil(data) // 2 * 2)

Remember that the line import numpy as np is necessary.

The output of rounded_data after data frame:

dfRounded = pd.DataFrame(rounded_data, columns=[&#39;Onset&#39;])

print(dfRounded)

is:

    Onset
0   290.0
1   498.0
2   810.0
3  1164.0

Finally, if you want to convert the values to integers you can use:

dfRounded[&#39;Onset&#39;] = dfRounded[&#39;Onset&#39;].astype(int)

答案5

得分: 0

我建议创建一个函数,使用 math.floor 来将数字四舍五入到最接近的偶数,然后将其应用于你的数据框:

def even_round_down(number):
    if number % 2 == 0:
        return np.floor(number)
    else:
        return np.floor(number / 2) * 2

你可以这样做:

df['Onset'] = df['Onset'].apply(even_round_down)
英文:

I would suggest creating a function that rounds to the nearest even (with math.floor) and then applying it to your data frame:

   def even_round_down(number):
    if number % 2 == 0:
        return np.floor(number)
    else:
        return np.floor(number / 2) * 2

You can do:

df[&#39;Onset&#39;] = df[&#39;Onset&#39;].apply(even_round_down)

huangapple
  • 本文由 发表于 2023年6月29日 02:58:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76575992.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定