[英]How to replace string values of a Pandas column with a string except some values?
[英]pandas replace column values except one
原始數據框:
DocID DocURL DocName SiteURL LibraryURL
0 29806 path/to/doc/docname1.doc docname1 web/url lib/url
1 29807 path/to/doc/docname2.doc docname2 web/url lib/url
新數據框:
DocURL DocName SiteURL LibraryURL
0 path/to/doc/newname.doc newname web/url lib/url
我想用這個新行替換 DocID == 29806 的行。
我曾嘗試使用以下代碼進行操作,但沒有成功:
df.loc[:, df.columns != 'DocID'].loc[row_index] = new_df.iloc[0]
和這個:
df.loc[row_index][1:] = new_df.iloc[0]
對於第一個我沒有收到任何錯誤或警告,對於下一個我得到:
試圖在來自 DataFrame 的切片副本上設置值
現在,我希望/需要將原始數據幀中的行替換為新數據幀的行,但我需要保持 DocID 不變。 我還需要將結果存儲在原始數據框中。
一種方法是創建要替換的列列表,然后使用to_numpy
來避免任何對齊問題,例如:
cols_replace = ['DocURL','DocName','SiteURL','LibraryURL']
df.loc[row_index, cols_replace] = new_df.loc[0, cols_replace].to_numpy()
只需使用df.update()
即可獲得所需內容。
代碼:
df=pd.DataFrame({'DocID':[29806,29807],'DocURL':['path/to/doc/docname1.doc','path/to/doc/docname2.doc'],
'DocName':['docname1','docname2'],'SiteURL':['web/url','web/url'],
'LibraryURL':['lib/url','lib/url']})
df2=pd.DataFrame({'DocURL':['path/to/doc/newname.doc'],
'DocName':['newname'],'SiteURL':['web/url'],
'LibraryURL':['lib/url']})
df.update(df2)
輸出:
DocID DocURL DocName SiteURL LibraryURL
0 29806 path/to/doc/newname.doc newname web/url lib/url
1 29807 path/to/doc/docname2.doc docname2 web/url lib/url
在這種情況下, df.update()
將使用df2
的新值更新df
的原始值。 更新將基於索引完成。 因此,請確保df2
中的索引號與df
的索引號匹配。
嘗試這個:
df.loc[df['DocID'] == '29806', ['DocURL', 'DocName', 'SiteURL', 'LibraryURL']] = dfNew.iloc[0]['DocURL', 'DocName', 'SiteURL', 'LibraryURL']
new_df["DocID"] = [29806]
old_df.set_index("DocID")
new_df.set_index("DocID")
old_df.update(new_df)
最好的辦法是將DocID
列添加到新數據框中,並使用您要更新的舊數據框中的 DocID 填充它。 然后,將DocID
設置為索引。 最后,調用.update
默認對齊索引,並且行為是完全受控的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.