Python中pandas怎么替换指定数据?如何替换pandas指定数据?

这篇文章主要讲解了“Python中pandas怎么替换指定数据?如何替换pandas指定数据?”文章简单易懂,便于理解,下面请大家跟着我的思路慢慢深入,一起来研究和学习“Python pandas怎么替换指定数据”吧!

Python中pandas怎么替换指定数据?如何替换pandas指定数据?

文章插图
一、构造dataframe
在DataFrame中读出数据显示为NaN或者NaT(缺失时间),举个例子:
import pandas as pdimport numpy as npdf=pd.DataFrame(np.arange(16).reshape(4,4),columns=["sj","gd",”zz” ,"gz"],index=["one","two","three","four"])df.iloc[0,1]=np.nandf输出结果:
sj gd zz gz
one 0 NaN 2 3
two 2 3.0 4 5
three 4 5.0 6 7
four 8 9.0 10 11
二、替换指定数据,使用方法fillna、isin、replace
1、用"sj"列的同行数据将"gd"列的空值替换掉
df["sj"].fillna(df["gd"],inplace=True)sj gd zz gz
one 0 2.0 2 3
two 2 3.0 4 5
three 4 5.0 6 7
four 8 9.0 10 11
2、在1的基础上,将"zz"列为2或者6的数据替换成-2
【Python中pandas怎么替换指定数据?如何替换pandas指定数据?】方法一:可以直接替换
df.loc[df["zz"].isin([2,6]),"zz"]=-2s jgd zz gz
one 0 2.0 -2 3
two 2 3.0 4 5
three 4 5.0 -2 7
four 8 9.0 10 11
方法二:可以用函数replace()替换
df.replace({"zz":{2:-2,6:-2}},inplace=True)sj gd zz gz
one 0 2.0 -2 3
two 2 3.0 4 5
three 4 5.0 -2 7
four 8 9.0 10 11
三、替换函数replace()详解
原来的dataframe数据如下:
sj gd zz gz
one 0 郑州 2 3
two 2 3.0 4 5
three 4 5.0 6 7
four 8 9.0 10 11
1、全局替换元素
1)替换单个元素
df.replace(4,0)#将所有的4元素替换为0,返回dataframesj gd zz gz
one 0 郑州 2 3
two 2 3.0 0 5
three 0 5.0 6 7
four 8 9.0 10 11
2)替换多个元素
方法一:在字典中指定
df.replace({4:0,2:1})#将-4替换为0,4替换为1sj gd zz gz
one 0 郑州 1 3
two 1 3.0 0 5
three 0 5.0 6 7
four 8 9.0 10 11
方法二:在列表中指定,如果多个元素替换为相同的值,会更方便 。
df.replace([4,2],[0,1])#将4替换为0,2替换为1sj gd zz gz
one 0 郑州 1 3
two 1 3.0 0 5
three 0 5.0 6 7
four 8 9.0 10 11
2、通过指定条件替换元素
df.replace({"gd":{8:18,1:11},"zz":{5.0:50}})#将"gd"列的8替换为18,1替换为11,将zz列的5替换为50

sj gd zz gz
one 0 郑州  13
two 11 3.0 0 5
three0 50 6 7
four 18 9.0 10 11
还可以通过直接索引列的方式来替换指定列的元素
df["gd"].replace({0:10,18:50})#将"gd"列的0替换为10,18替换为50

sj gd zz gz
one 10 郑州 1 3
two 11 3.0 0 5
three 0 50 6 7
four 50 9.0 10 11
以上就是“Python中pandas怎么替换指定数据?如何替换pandas指定数据?”的内容了,想要深度了解,还需要大家动手操作,想要了解更多知识,可以继续关注哦!

    推荐阅读