• Python学习笔记:replace方法替换字符


    一、字符串替换

    replace() 方法用于替换字符串。语法为:

    string.replace(oldvalue, newvalue, count)
    
    • oldvalue -- 待替换字符串
    • newvalue -- 替换字符串
    • count -- 指定次数 默认所有
    # 普通用法
    txt = "I like bananas"
    x = txt.replace("bananas", "apple")
    print(x)
    # I like apple
    
    # 全部替换
    txt = "one one was a race horse, two two was one too."
    x = txt.replace("one", "three")
    print(x)
    # three three was a race horse, two two was three too.
    
    # 指定替换次数
    txt = "one one was a race horse, two two was one too."
    x = txt.replace("one", "three", 2)
    print(x)
    # three three was a race horse, two two was one too.
    

    二、pd.replace替换

    pd.replace 实现批量替换,处理数据。语法为:

    df.replace(to_replace, value)
    

    1.普通替换

    • 替换数据并修改原始数据
    import pandas as pd
    import numpy as np
    df = pd.DataFrame({"a":['小李','小白','大黄'],
                      "b":[1,2,3],
                      "c":[4,5,6],
                      "d":["A","A","BB"]})
    df
    '''
    	a	b	c	d
    0	小李	1	4	A
    1	小白	2	5	A
    2	大黄	3	6	BB
    '''
    
    # 替换(未修改源数据)
    df.replace("小白", "小黑")
    '''
    
    a	b	c	d
    0	小李	1	4	A
    1	小黑	2	5	A
    2	大黄	3	6	BB
    '''
    
    # 替换并修改源数据
    df.replace("小白", "小黑", inplace=True)
    
    • 替换某列数据
    df['a'].replace("小黑", "小X", inplace=True)
    
    • 利用字典的形式替换多个数值

    字典中的键作为原始值,字典里的值作为替换后的值。

    df.replace({'A':'B', 1:100})
    '''
    	a	b	c	d
    0	小李	100	4	B
    1	小X	2	5	B
    2	大黄	3	6	BB
    '''
    
    • 利用列表的形式替换
    df.replace(['A',1], ['B',100])
    '''
    
    a	b	c	d
    0	小李	100	4	B
    1	小X	2	5	B
    2	大黄	3	6	BB
    '''
    
    df.replace(['A',1], 1000) # 替换后值一致
    
    • 指定列替换部分内容
    df['a'] = df['a'].str.replace('小', '巨')
    print(df)
    '''
        a  b  c   d
    0  巨李  1  4   A
    1  巨X  2  5   A
    2  大黄  3  6  BB
    '''
    

    使用 str.replace 时不能使用 inplace=True 参数,因此需要改成赋值。

    2.正则表达式替换

    正则表达式很强大,可以实现一次替换多个不同的值。

    df.replace('[A-Z]', '厉害', regex=True)
    # 必须指定参数 regex=True
    

    缺失值替换时考虑 fillna() 进行填充,功能更加强大,可实现前后填充、近邻填充、插值填充等。

    参考链接:Python 字符串 replace() 方法

    参考链接:python replace 用法

  • 相关阅读:
    解析SQL Server之任务调度
    Sqlserver (转载)事物与锁
    浅谈SQL Server数据内部表现形式
    浅谈SQL Server事务与锁(上篇)
    如何查看某个查询用了多少TempDB空间
    Select count(*)和Count(1)的区别和执行方式
    zookeeper 源码(二) session 和 处理事务请求
    zookeeper 源码(一) 选举和同步数据
    分布式一致性协议 --- Paxos
    分布式事务 --- 2PC 和 3PC
  • 原文地址:https://www.cnblogs.com/hider/p/15230909.html
Copyright © 2020-2023  润新知