簡體   English   中英

我想使用其他列中的值替換數據框中的一部分列值

[英]I want to replace part of a column value in a dataframe using values from other columns

我有一列,其中該列的一部分將被另一列的值替換。 例如,我想從此開始:

 <table style="width:100%" border="1"> <tr> <th>Reference</th> <th>Identification\\Customer</th> <th>Target Customer</th> </tr> <tr> <td>CustomerA\\BFG\\CustomerA-CCP\\CustomerA-CSA</td> <td>CustomerA</td> <td>CustomerB</td> </tr> </table> 

對此

 <table style="width:100%" border="1"> <tr> <th>Reference </th> <th>Identification\\Customer</th> <th>Target Customer</th> </tr> <tr> <td>Customer<a style="color:red;">B</a>\\BFG\\CustomerA-CCP\\CustomerA-CSA</td> <td>CustomerA</td> <td>CustomerB</td> </tr> </table> 

我只希望將CustomerA的初始值更改為CustomerB。 其余值應保持不變。

我以為這應該可行,但我在專欄中獲得了所有答案

data = [['CustomerA\\BFG\\CustomerA-CCP\\CustomerA-Agreement',  'CustomerA',    'CustomerB'],['CustomerC\\BFG\\CustomerC-CCP\\CustomerC-Agreement', 'CustomerC',    'CustomerD']] 

customerCollateral = pd.DataFrame(data, columns = ['Reference', 'Identification\\Customer','Identification\\Parent']) 

customerCollateral['Reference2']=customerCollateral.apply(lambda x:x['Reference'].replace(x['Identification\\Customer'],x['Identification\\Parent'],n=1),axis=1)

print(customerCollateral)

但是,當我運行上面的我得到這個錯誤。 TypeError :(“ replace()不帶關鍵字參數”,“發生在索引0”)

如果我不使用n = 1,則將CustomerA的所有值替換為CustomerB的十個值。

x['Reference']是有問題的對象,因為x是一個Series,並且已經按名稱查詢過。 replace(...)調用的對象是str

但是, str.replace沒有關鍵字n 請參閱此處的文檔,限制由第三個參數而不是關鍵字參數定義: https : //docs.python.org/3/library/stdtypes.html#str.replace

customerCollateral['Reference'] = customerCollateral['Identification\Parent'].str.cat(customerCollateral['Reference'].str.extract(r"(\\.*)"))

只需以正確的順序連接所需的字符串即可。 我提取了我們想要的參考列部分,並添加了id / parent列。

暫無
暫無

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

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