網站首頁 編程語言 正文
pandas中可以使用round(n)方法返回 x 的小數點四舍五入到n個數字。簡潔的說就是,四舍五入的保留小數點后的幾個數字。round()不添加任何參數的時候,等同于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))
我們經常需要對有浮點數的列需要保持精度,那么在pandas中該如何實現呢?這里提供一種方法,round方法
round常用用法有兩種方式:
1、傳入int,對所有列保持統一精度
>>> 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
# 統一保持2位小數
>>> 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
# 統一保持一位小數
>>> 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,對指定列設置精度,key為列名,value為精度
# 指定列名設置精度,未指定的則保持原樣
>>> 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
# 兩列分別設置不同的精度
>>> 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
相關推薦
- 2022-06-09 Python字符串的轉義字符_python
- 2022-03-28 Python垃圾回收及Linux?Fork_python
- 2023-02-01 MongoDB?事務支持詳解_MongoDB
- 2022-12-26 Python中pywifi模塊的基本用法講解_python
- 2022-03-14 workman實現websocket聊天nginx的配置
- 2022-07-30 react中受控組件與非受控組件
- 2021-10-24 Linux多線程中fork與互斥鎖過程示例_Linux
- 2023-12-08 IDEA中, Maven不顯示插件 mybatis-generator
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支