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 用法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM