我正在嘗試在我的“網站”列中為網址添加前綴。我不知道如何防止幫助列的每次新迭代都覆寫前一列中的所有內容。
例如說我的專欄中有以下網址:
http://www.bakkersfinedrycleaning.com/
www.cbgi.org
barstoolsand.com
這將是所需的最終狀態:
http://www.bakkersfinedrycleaning.com/
http://www.cbgi.org
http://www.barstoolsand.com
這是我所能得到的最接近的:
def nan_to_zeros(df, col):
new_col = f"nanreplace{col}"
df[new_col] = df[col].fillna('~')
return df
df1 = nan_to_zeros(df1, 'Website')
df1['url_helper'] = df1.loc[~df1['nanreplaceWebsite'].str.startswith('http')| ~df1['nanreplaceWebsite'].str.startswith('www'), 'url_helper'] = 'https://www.'
df1['url_helper'] = df1.loc[df1['nanreplaceWebsite'].str.startswith('http'), 'url_helper'] = ""
df1['url_helper'] = df1.loc[df1['nanreplaceWebsite'].str.startswith('www'),'url_helper'] = 'www'
print(df1[['nanreplaceWebsite',"url_helper"]])
這只是給了我一個幫助列,www因為最后一次迭代覆寫了所有欄位。任何方向表示贊賞。
資料:
{'Website': ['http://www.bakkersfinedrycleaning.com/',
'www.cbgi.org', 'barstoolsand.com']}
uj5u.com熱心網友回復:
IIUC,這里有 3 件事需要解決:
df1['url_helper'] =不應該在那里|應該&在第一個條件中,因為'https://www.'應該添加到不以條件中的任何字串開頭的 URL。如果我們在其他兩個條件之后檢查第一個條件,錯誤將變得明顯。最后一個條件應該添加
"http://"而不是"www".
或者,您的問題可以使用np.select. 傳入條件串列中的多個條件及其對應的選擇串列,并相應地賦值:
import numpy as np
s = df1['Website'].fillna('~')
df1['fixed Website'] = np.select([~(s.str.startswith('http') | ~s.str.contains('www')),
~(s.str.startswith('http') | s.str.contains('www'))
],
['http://' s, 'http://www.' s], s)
輸出:
Website fixed Website
0 http://www.bakkersfinedrycleaning.com/ http://www.bakkersfinedrycleaning.com/
1 www.cbgi.org http://www.cbgi.org
2 barstoolsand.com http://www.barstoolsand.com
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/427577.html
上一篇:計算大型資料框中的不同字符
下一篇:為什么我的資料框的條件不起作用?
