Python pandas 替换指定数据 | 您所在的位置:网站首页 › dataframe众数 › 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
1、用"sz"列的同行数据将"bj"列的空值替换掉 df["bj"].fillna(df["sz"],inplace=True)
原dataframe如下: 1、全局替换元素 1)替换单个元素 df.replace(-4,0)#将所有的-4元素替换为0,返回dataframe
法二:在列表中指定 df.replace([-4,4],[0,1])#将-4替换为0,4替换为1
3、通过模糊条件替换指定元素 法一:通过字符串方法替换 str.replace() df["bj"]=df["bj"].str.replace("北","南").fillna(df["bj"])#将"bj"列中的"北"字替换成"南"字,若无"北"值,则不替换
最后,如果需要在原始数据上完成替换,可以通过设置参数inplace=True。 参考链接: https://blog.csdn.net/qq_18351157/article/details/107141339 |
CopyRight 2018-2019 实验室设备网 版权所有 |