如何以一系列精度舍入一系列熊猫值?

我正在尝试用 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'>

有没有办法在不遍历每一行的情况下做到这一点?


绝地无双
浏览 123回答 2
2回答

慕无忌1623718

In [45]: df.apply(lambda x: round(x["value"], int(x["precision"])), axis=1)Out[45]:0&nbsp; &nbsp; 1.101&nbsp; &nbsp; 2.222&nbsp; &nbsp; 3.333&nbsp; &nbsp; 4.40

拉丁的传说

使用列表理解将变量传递给np.round&nbsp; df = pd.DataFrame({'value': [1.111, 2.222, 3.333, 4.444], 'precision': [1,2,3,1]})print(df)&nbsp;value&nbsp; precision0&nbsp; 1.111&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 11&nbsp; 2.222&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 22&nbsp; 3.333&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 33&nbsp; 4.444&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1df['rounded'] = [np.around(x,y) for x,y in zip(df['value'],df['precision'])]print(df)&nbsp; &nbsp; value&nbsp; precision&nbsp; rounded0&nbsp; 1.111&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1&nbsp; &nbsp; 1.1001&nbsp; 2.222&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 2&nbsp; &nbsp; 2.2202&nbsp; 3.333&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 3&nbsp; &nbsp; 3.3333&nbsp; 4.444&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1&nbsp; &nbsp; 4.400
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python