用 pandas 舍入数字

发布于 01-16 02:28 字数 376 浏览 1 评论 0原文

我有一个 pandas 数据框,其中有一列包含数字: [4.534000e-01, 6.580000e-01, 1.349300e+00, 2.069180e+01, 3.498000e-01,...]

我想将此列四舍五入到小数点后 3 位,例如我使用 round(col) 函数;但是,我注意到 panda 给了我以下内容: [0.453, 0.658, 1.349, 20.692, 0.35,...] 其中最后一个元素的小数点后没有三位数字。

我希望将所有数字四舍五入为相同数量的数字,例如:[0.453, 0.658, 1.349, 20.692, 0.350,...]

如何在 pandas 中做到这一点?

I have a pandas dataframe with a column that contains the numbers:
[4.534000e-01, 6.580000e-01, 1.349300e+00, 2.069180e+01, 3.498000e-01,...]

I want to round this column up to 3 decimal places, for which I use the round(col) function; however, I have noticed that panda gives me the following:
[0.453, 0.658, 1.349, 20.692, 0.35,...]
where the last element doesn't have three digits after the decimal.

I would like to have all the numbers rounded with the same amount of digits, for example, like: [0.453, 0.658, 1.349, 20.692, 0.350,...].

How can be done this within pandas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

丿*梦醉红颜2025-01-23 02:28:23

您可以使用pandas.DataFrame.round来指定精度。

https://pandas.pydata.org/docs/reference/ api/pandas.DataFrame.round.html

import pandas as pd

# instantiate dataframe
dataframe = pd.DataFrame({'column_to_round': [4.534000e-01, 6.580000e-01, 1.349300e+00, 2.069180e+01, 3.498000e-01,]})

# create a new column with this new precision
dataframe['set_decimal_level'] = dataframe.round({'column_to_round': 3})


You can use pandas.DataFrame.round to specify a precision.

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.round.html

import pandas as pd

# instantiate dataframe
dataframe = pd.DataFrame({'column_to_round': [4.534000e-01, 6.580000e-01, 1.349300e+00, 2.069180e+01, 3.498000e-01,]})

# create a new column with this new precision
dataframe['set_decimal_level'] = dataframe.round({'column_to_round': 3})


俏︾媚2025-01-23 02:28:23
import pandas as pd    
df = pd.DataFrame([4.534000e-01, 6.580000e-01, 1.349300e+00, 2.069180e+01, 3.498000e-01], columns=['numbers'])
df.round(3)

印刷:

0.453 0.658 1.349 20.692 0.350

import pandas as pd    
df = pd.DataFrame([4.534000e-01, 6.580000e-01, 1.349300e+00, 2.069180e+01, 3.498000e-01], columns=['numbers'])
df.round(3)

Prints:

0.453 0.658 1.349 20.692 0.350

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文