如何以一系列精度对熊猫值系列进行四舍五入?

时间:2020-07-14 22:22:07

标签: python pandas rounding

我正在尝试使用1列值和1列精度舍入一个DataFrame。

>>> df = pd.DataFrame({'value': [1.111, 2.222, 3.333, 4.444], 'precision': [1,2,2,1]})
>>> df
   precision  value
0          1  1.111
1          2  2.222
2          2  3.333
3          1  4.444

要创建一个rounded列,如下所示:

>>> df
   precision  value  rounded
0          1  1.111     1.1
1          2  2.222     2.22
2          2  3.333     3.33
3          1  4.444     4.4

我尝试了直观的解决方案:

>>> df['rounded'] = round(df['value'], df['precision'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/Drew/Library/Python/2.7/lib/python/site-packages/pandas/core/series.py", line 93, in wrapper
    "{0}".format(str(converter)))
TypeError: cannot convert the series to <type 'float'>

>>> df['rounded'] = df['value'].round(df['precision'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/Drew/Library/Python/2.7/lib/python/site-packages/pandas/core/series.py", line 1999, in round
    result = com.values_from_object(self).round(decimals)
  File "/Users/Drew/Library/Python/2.7/lib/python/site-packages/pandas/core/series.py", line 93, in wrapper
    "{0}".format(str(converter)))
TypeError: cannot convert the series to <type 'int'>

有没有一种方法可以不遍历每一行?

2 个答案:

答案 0 :(得分:2)

In [45]: df.apply(lambda x: round(x["value"], int(x["precision"])), axis=1)
Out[45]:
0    1.10
1    2.22
2    3.33
3    4.40

答案 1 :(得分:1)

使用列表推导将变量传递到np.round

  df = pd.DataFrame({'value': [1.111, 2.222, 3.333, 4.444], 'precision': [1,2,3,1]})
print(df)

 value  precision
0  1.111          1
1  2.222          2
2  3.333          3
3  4.444          1

df['rounded'] = [np.around(x,y) for x,y in zip(df['value'],df['precision'])]
print(df)


    value  precision  rounded
0  1.111          1    1.100
1  2.222          2    2.220
2  3.333          3    3.333
3  4.444          1    4.400