網(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
相關(guān)推薦
- 2022-04-28 C#網(wǎng)絡(luò)編程之Socket編程_C#教程
- 2022-08-05 unsupported media type 415
- 2022-05-20 關(guān)于Mybatis-plus中PaginationInterceptor分頁(yè)攔截器過(guò)時(shí)問(wèn)題解決辦法
- 2022-03-31 C語(yǔ)言運(yùn)算符的重載詳解_C 語(yǔ)言
- 2023-07-02 Python中星號(hào)的五種用法小結(jié)_python
- 2022-12-30 解決React報(bào)錯(cuò)Style?prop?value?must?be?an?object_React
- 2022-08-20 Docker容器修改端口映射的實(shí)現(xiàn)_docker
- 2022-11-27 關(guān)于HTTPS端口443的技術(shù)講解(什么是443端口)_服務(wù)器其它
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門(mén)
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支