簡體   English   中英

Pandas數據框部分字符串替換

[英]Pandas Data Frame Partial String Replace

鑒於此數據框架:

import pandas as pd
d=pd.DataFrame({'A':['a','b',99],'B':[1,2,'99'],'C':['abcd99',4,5]})
d

    A   B   C
0   a   1   abcd*
1   b   2   4
2   99  99  5

我想用星號替換整個數據框中的所有99個。 我試過這個:

d.replace('99','*')

...但它只適用於B列中的字符串99。

提前致謝!

如果要替換所有99秒,請嘗試使用正則表達式

>>> d.astype(str).replace('99','*',regex=True)

    A   B   C
0   a   1   abcd*
1   b   2   4
2   *   *   5

這將完成工作:

import pandas as pd
d=pd.DataFrame({'A':['a','b',99],'B':[1,2,'99'],'C':['abcd99',4,5]})
d=d.astype(str)
d.replace('99','*',regex=True)

這使

    A   B   C
0   a   1   abcd*
1   b   2   4
2   *   *   5

請注意,這會創建一個新的數據幀。 你也可以這樣做:

d.replace('99','*',regex=True,inplace=True)

問題是A列中的值99 ,B列的類型不同:

>>> type(d.loc[2,"A"])
<class 'int'>
>>> type(d.loc[2,"B"])
<class 'str'>

您可以通過df.astype()將數據幀轉換為字符串類型然后替換,從而導致:

>>> d.astype(str).replace("99","*")
   A  B       C
0  a  1  abcd99
1  b  2       4
2  *  *       5

編輯:使用正則表達式是其他答案給出的正確解決方案。 我出於某種原因錯過了你的DataFrame中的abcd *。

將它留在這里,以防它對其他人有幫助。

使用numpy的字符函數

d.values[:] = np.core.defchararray.replace(d.values.astype(str), '99', '*')
d

   A  B      C
0  a  1  abcd*
1  b  2      4
2  *  *      5

天真的時間測試

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM