pandas 将系列转换为整数时四舍五入

pandas rounding when converting the series to int

如何根据分配的系列舍入小数位数? 我的样本数据是这样的:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.uniform(1,5,size=(10,1)), columns=['Results'])
df['groups'] = ['A', 'B', 'C', 'D']
df['decimal'] = [1, 0, 2, 3]

这会生成如下数据框:

   Results    groups  decimal  
0  2.851325      A        1
1  1.397018      B        0
2  3.522660      C        2
3  1.995171      D        3

接下来:每个结果数字需要四舍五入到decimal所示的小数位数。我在下面尝试的结果导致 TypeError: cannot convert the series to <class 'int'>

错误
df['new'] = df['Results'].round(df['decimal'])

我想要这样的结果:

   Results     groups decimal new
0  2.851325      A        1   2.9
1  1.397018      B        0   1
2  3.522660      C        2   3.52
3  1.995171      D        3   1.995

您可以将 dict-like 对象传递给 DataFrame.round 来为不同的列设置不同的精度级别。所以需要转置一个单列DataFrame(由Results列构造)两次:

df['Results'] = df[['Results']].T.round(df['decimal']).T

另一种选择是列表理解:

df['Results'] = [round(num, rnd) for num, rnd in zip(df['Results'], df['decimal'])]

输出:

   Results groups  decimal
0    2.500      A        1
1    2.000      B        0
2    2.190      C        2
3    1.243      D        3

请注意,由于它是单列,因此它的小数位由最高位小数决定;但是如果你查看这个 DataFrame 的构造函数,你会发现精度确实发生了变化:

>>> df[['Results']].to_dict('list')
{'Results': [2.5, 2.0, 2.19, 1.243]}

试试这个:

df['new']=df['Results'].copy()
df=df.round({'new': 1})