对pandas replace函数的使用方法小结
作者:每天进步一点点2017 时间:2022-07-04 15:20:24
语法:replace(self, to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad', axis=None)
使用方法如下:
import numpy as np
import pandas as pd
df = pd.read_csv('emp.csv')
df
#Series对象值替换
s = df.iloc[2]#获取行索引为2数据
#单值替换
s.replace('?',np.nan)#用np.nan替换?
s.replace({'?':'NA'})#用NA替换?
#多值替换
s.replace(['?',r'$'],[np.nan,'NA'])#列表值替换
s.replace({'?':np.nan,'$':'NA'})#字典映射
#同缺失值填充方法类似
s.replace(['?','$'],method='pad')#向前填充
s.replace(['?','$'],method='ffill')#向前填充
s.replace(['?','$'],method='bfill')#向后填充
#limit参数控制填充次数
s.replace(['?','$'],method='bfill',limit=1)
#DataFrame对象值替换
#单值替换
df.replace('?',np.nan)#用np.nan替换?
df.replace({'?':'NA'})#用NA替换?
#按列指定单值替换
df.replace({'EMPNO':'?'},np.nan)#用np.nan替换EMPNO列中?
df.replace({'EMPNO':'?','ENAME':'.'},np.nan)#用np.nan替换EMPNO列中?和ENAME中.
#多值替换
df.replace(['?','.','$'],[np.nan,'NA','None'])##用np.nan替换?用NA替换. 用None替换$
df.replace({'?':'NA','$':None})#用NA替换? 用None替换$
df.replace({'?','$'},{'NA',None})#用NA替换? 用None替换$
#正则替换
df.replace(r'\?|\.|\$',np.nan,regex=True)#用np.nan替换?或.或$原字符
df.replace([r'\?',r'\$'],np.nan,regex=True)#用np.nan替换?和$
df.replace([r'\?',r'\$'],[np.nan,'NA'],regex=True)#用np.nan替换?用NA替换$符号
df.replace(regex={r'\?':None})
#value参数显示传递
df.replace(regex=[r'\?|\.|\$'],value=np.nan)#用np.nan替换?或.或$原字符
来源:https://blog.csdn.net/kancy110/article/details/72719340
标签:pandas,replace
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
对python字典过滤条件的实例详解
2022-01-28 14:02:30
Python 串口读写的实现方法
2021-04-24 13:25:12
![](https://img.aspxhome.com/file/2023/4/71994_0s.jpg)
MySQL教程:Group By用法
2009-02-26 15:27:00
python实现微信远程控制电脑
2023-07-07 07:43:43
![](https://img.aspxhome.com/file/2023/7/112147_0s.png)
Vue watch原理源码层深入讲解
2024-04-30 10:40:58
![](https://img.aspxhome.com/file/2023/3/130093_0s.png)
OpenCV实现常见的四种图像几何变换
2022-11-08 11:20:50
![](https://img.aspxhome.com/file/2023/6/109666_0s.jpg)
XML to DDL的项目关键:与数据库同步
2008-05-29 14:19:00
js自动闭合html标签(自动补全html标记)
2023-08-25 07:06:35
Python 读写文件的操作代码
2021-11-16 02:43:44
PHP获取类中常量,属性,及方法列表的方法
2023-11-19 19:57:58
SQL server不支持utf8 php却用utf8的矛盾问题解决方法
2023-07-20 12:01:28
Python使用背景差分器实现运动物体检测
2023-06-21 09:37:22
![](https://img.aspxhome.com/file/2023/9/95279_0s.jpg)
Django Admin后台添加数据库视图过程解析
2024-01-27 06:40:17
![](https://img.aspxhome.com/file/2023/5/90575_0s.png)
python实现壁纸批量下载代码实例
2023-11-15 12:38:54
![](https://img.aspxhome.com/file/2023/4/64594_0s.png)
keras实现调用自己训练的模型,并去掉全连接层
2023-08-10 16:34:21
Python中gevent模块协程使用
2023-10-23 02:56:46
压缩包密码破解示例分享(类似典破解)
2022-10-17 17:03:37
自动生成sql语句
2008-05-09 12:42:00
如何获取Python简单for循环索引
2023-11-17 13:50:08
mysql 字符串正则表达式及说明
2024-01-13 17:47:59