亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

絕地無雙 2023-03-08 17:28:40
我正在嘗試用 1 列值和 1 列精度對 DataFrame 進行舍入。>>> df = pd.DataFrame({'value': [1.111, 2.222, 3.333, 4.444], 'precision': [1,2,2,1]})>>> df   precision  value0          1  1.1111          2  2.2222          2  3.3333          1  4.444要創建rounded這樣的列:>>> df   precision  value  rounded0          1  1.111     1.11          2  2.222     2.222          2  3.333     3.333          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 回答

?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

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


查看完整回答
反對 回復 2023-03-08
?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

使用列表理解將變量傳遞給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


查看完整回答
反對 回復 2023-03-08
  • 2 回答
  • 0 關注
  • 109 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號