日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

pandas?round方法保留兩位小數(shù)的設(shè)置實(shí)現(xiàn)_python

作者:data_amateur ? 更新時(shí)間: 2022-10-12 編程語(yǔ)言

pandas中可以使用round(n)方法返回 x 的小數(shù)點(diǎn)四舍五入到n個(gè)數(shù)字。簡(jiǎn)潔的說(shuō)就是,四舍五入的保留小數(shù)點(diǎn)后的幾個(gè)數(shù)字。round()不添加任何參數(shù)的時(shí)候,等同于round(0)就是取整。直接看例子:

import pandas as pd
import numpy as np
df_round = pd.DataFrame(np.random.random([3, 3]),
     columns=['A', 'B', 'C'], index=['one', 'two', 'three'])
df_round = df_round*10
print(df_round)
print(df_round.round(2))

我們經(jīng)常需要對(duì)有浮點(diǎn)數(shù)的列需要保持精度,那么在pandas中該如何實(shí)現(xiàn)呢?這里提供一種方法,round方法

round常用用法有兩種方式:

1、傳入int,對(duì)所有列保持統(tǒng)一精度

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame([(.21, .32), (.01, .6), (.66, .03), (.21, .183)],columns=['dogs', 'cats'])
>>> df
? ?dogs ? cats
0 ?0.21 ?0.320
1 ?0.01 ?0.600
2 ?0.66 ?0.030
3 ?0.21 ?0.183

# 統(tǒng)一保持2位小數(shù)
>>> df.round(2)
? ?dogs ?cats
0 ?0.21 ?0.32
1 ?0.01 ?0.60
2 ?0.66 ?0.03
3 ?0.21 ?0.18

# 統(tǒng)一保持一位小數(shù)
>>> df.round(1)
? ?dogs ?cats
0 ? 0.2 ? 0.3
1 ? 0.0 ? 0.6
2 ? 0.7 ? 0.0
3 ? 0.2 ? 0.2
>>>?

2、傳入dict,對(duì)指定列設(shè)置精度,key為列名,value為精度

# 指定列名設(shè)置精度,未指定的則保持原樣
>>> df.round({'dogs': 2})
   dogs   cats
0  0.21  0.320
1  0.01  0.600
2  0.66  0.030
3  0.21  0.183
# 兩列分別設(shè)置不同的精度
>>> df.round({'dogs':2, 'cats':1})
   dogs  cats
0  0.21   0.3
1  0.01   0.6
2  0.66   0.0
3  0.21   0.2

原文鏈接:https://blog.csdn.net/lost0910/article/details/104397869

欄目分類(lèi)
最近更新