文章目录
replace():替换
语法:字符串序列.replace(旧字串,新字串,替换次数)
注意:替换数次如果超过了字串的出现次数,就替换所有字串。
替换全部或者某一行
一、整个表全部替换
数据
示例
import pandas as pd
path='C:/Users/Admin/Desktop/pandas/替换.xlsx'
data=pd.read_excel(path)
data.replace('城八区','海淀区',inplace=True)
print(data)
二、某一列替换
import pandas as pd
path='C:/Users/Admin/Desktop/pandas/替换.xlsx'
data=pd.read_excel(path)
#data.replace('城八区','海淀区',inplace=True)
data['城市2'].replace('城八区','海淀区',inplace=True)
print(data)
替换指定的某个或多个数值(用字典的形式)
import pandas as pd
path='C:/Users/Admin/Desktop/pandas/替换.xlsx'
data=pd.read_excel(path)
dic={'A':20,'B':30}
data.replace(dic,inplace=True)
print(data)
用列表方式
import pandas as pd
path='C:/Users/Admin/Desktop/pandas/替换.xlsx'
data=pd.read_excel(path)
data.replace(['A','B'],[20,30],inplace=True)
print(data)
如果想替换的新值一样
import pandas as pd
path='C:/Users/Admin/Desktop/pandas/替换.xlsx'
data=pd.read_excel(path)
data.replace(['A','B'],20,inplace=True)
print(data)
替换某个数据的部分内容
import pandas as pd
path='C:/Users/Admin/Desktop/pandas/替换.xlsx'
data=pd.read_excel(path)
data['城市']=data['城市'].str.replace('城八','市')
print(data)
正则表达式替换
import pandas as pd
path='C:/Users/Admin/Desktop/pandas/替换.xlsx'
data=pd.read_excel(path)
data.replace('[A-Z]',88,regex=True,inplace=True)
print(data)