Python pandas 替换指定数据 | 您所在的位置:网站首页 › 列表如何替换 › Python pandas 替换指定数据 |
目录
一、构造dataframe二、替换指定数据(fillna、isin、replace)三、替换函数replace()详解
一、构造dataframe
import pandas as pd
import numpy as np
df=pd.DataFrame(np.arange(16).reshape(4,4),columns=["sh","bj","sz","gz"],index=["one","two","three","four"])
df.iloc[0,1]=np.nan
二、替换指定数据(fillna、isin、replace)
1、用"sz"列的同行数据将"bj"列的空值替换掉 df["bj"].fillna(df["sz"],inplace=True)2、在1的基础上,将"sz"列为2或者6的数据替换成-4 法一:直接替换 df.loc[df["sz"].isin([2,6]),"sz"]=-4法二:函数replace()替换 df.replace({"sz":{2:-4,6:-4}},inplace=True) 三、替换函数replace()详解原dataframe如下: 1、全局替换元素 1)替换单个元素 df.replace(-4,0)#将所有的-4元素替换为0,返回dataframe2)替换多个元素 法一:在字典中指定 df.replace({-4:0,4:1})#将-4替换为0,4替换为1法二:在列表中指定 df.replace([-4,4],[0,1])#将-4替换为0,4替换为1其中法二在列表中指定的方式,如果多个元素替换为相同的值,会更方便。 df.replace([-4,4],1)#将-4和4替换为12、通过指定条件替换元素 df.replace({"bj":{5:10,9:50},"gz":{7:10}})#将"bj"列的5替换为10,9替换为50,将gz列的7替换为10也可通过直接索引列的方式来替换指定列的元素 df["bj"].replace({5:10,9:50})#将"bj"列的5替换为10,9替换为503、通过模糊条件替换指定元素 法一:通过字符串方法替换 str.replace() df["bj"]=df["bj"].str.replace("北","南").fillna(df["bj"])#将"bj"列中的"北"字替换成"南"字,若无"北"值,则不替换法二:通过正则匹配替换 df.replace("(.*)北(.*)","南京",regex=True)#将"bj"列中的含有"北"字的元素替换成"南京"最后,如果需要在原始数据上完成替换,可以通过设置参数inplace=True。 参考链接: https://blog.csdn.net/qq_18351157/article/details/107141339 |
CopyRight 2018-2019 实验室设备网 版权所有 |