Python 修改筛选数据的4种方法及函数where()、replace()的用法介绍(附Python代码) |
您所在的位置:网站首页 › 芷兰简介 › Python 修改筛选数据的4种方法及函数where()、replace()的用法介绍(附Python代码) |
背景概述
原始数据的整理和清洁过程中,有时需要对符合某些条件要求的数据进行更新,如:对条件筛选出来的记录赋予新数值或字符串;按类别建立新的特征属性等,本文小结了修改或匹配数据记录方法。 方法与函数简介 replace()函数:找到对应的数值或字符串直接赋予新值:df.replace(old, new)where()函数:替换where条件为False的值:df.where(cond, x, y)使用索引值进行修改:df[“column_name”].iloc[index]使用字典进行匹配修改:df[“column_name”].map(dict) 示例代码(Python代码)1. replace()函数:直接查找并替换数值或字符串 – 如df.replace(old, new) DataFrame.replace(to_replace = None,value = None,inplace = False,limit = None,regex = False,method =‘pad’ ) 替换给定的值to_replace:str,regex,list,dict,Series,int,float或None 如果regex=True则to_replace里的所有字符串都将被解释为正则表达 import numpy as np import pandas as pd # 举例1: 对整个数据表中的某个数值或字符串直接修改 li = [[1, 100], [100, 30], [3, 100]] df = pd.DataFrame(li, columns=["A", "B"]) display(df) df = df.replace(100, "aa") df
2. where()函数:替换where条件为False的值 – 如df.where(cond, other) 或 df.where(cond, x, y) where(cond, other=nan, inplace=False, axis=None, level=None, errors=‘raise’, try_cast=False) 替换where条件为False的值,cond:bool Series/DataFrame, array-like,或 callable 当cond为True时,保持原始值。 当为False时,用other的相应值替换。 如果cond是可调用的,它将根据Series/DataFrame计算,并且应该返回boolean Series/DataFrame或array。 可调用对象不能更改输入Series/DataFrame(尽管panda不检查它)。 other:scalar, Series/DataFrame, 或 callable;cond为假的条目被替换为other的相应值。 # 举例3:where()函数在Series中的应用 # 将小于2的数据替换为100(即设定other=100,通常other默认为NaN) s = pd.Series(range(1, 6)) s.where(s > 2, 100)
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |