gpt4 book ai didi

python - pandas, numpy 四舍五入到最接近的 100

转载 作者:太空狗 更新时间:2023-10-30 02:01:49 26 4
gpt4 key购买 nike

我使用以下代码创建了一个数据框列,并试图弄清楚如何将其四舍五入到最接近的第 100 位。

...
# This prints out my new value rounded to the nearest whole number.
df['new_values'] = (10000/df['old_values']).apply(numpy.floor)

# How do I get it to round down to the nearest 100th instead?
# i.e. 8450 rounded to 8400

最佳答案

您需要除以 100,转换为 int,最后乘以 100:

df['new_values'] = (df['old_values'] / 100).astype(int) *100

同于:

df['new_values'] = (df['old_values'] / 100).apply(np.floor).astype(int) *100

示例:

df = pd.DataFrame({'old_values':[8450, 8470, 343, 573, 34543, 23999]})
df['new_values'] = (df['old_values'] / 100).astype(int) *100
print (df)
old_values new_values
0 8450 8400
1 8470 8400
2 343 300
3 573 500
4 34543 34500
5 23999 23900

编辑:

df = pd.DataFrame({'old_values':[3, 6, 89, 573, 34, 23]})
#show output of first divide for verifying output
df['new_values1'] = (10000/df['old_values'])
df['new_values'] = (10000/df['old_values']).div(100).astype(int).mul(100)
print (df)
old_values new_values1 new_values
0 3 3333.333333 3300
1 6 1666.666667 1600
2 89 112.359551 100
3 573 17.452007 0
4 34 294.117647 200
5 23 434.782609 400

关于python - pandas, numpy 四舍五入到最接近的 100,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46020761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com