我有一個包含某些列的資料框。我想再添加一個依賴于源列的列。資料框如下所示:
需要根據源值添加 year_23 列。
Fy_23 是基于源的靜態值。我是熊貓新手,需要一些關于如何實作它的建議
uj5u.com熱心網友回復:
另一個簡單的解決方案是創建一個空列并根據Source列值修改值:
df['year_23'] = np.nan
df['year_23'][df['Source']=='Google'] = 'text1'
df['year_23'][df['Source']=='Bing'] = 'text2'
uj5u.com熱心網友回復:
使用np.where
df["Year_23"] = np.where(df["Source"].eq("Google"), "x", "y")
uj5u.com熱心網友回復:
你可以像這樣定義一個函式:
def do_this(source):
if Source == 'Google':
return "The string you want"
else:
return "The string you want if above condition is not satisfied"
之后,從要應用更改的資料框中選擇列,并將其分配給所需的新列。
df['New Column'] = df['Column'].apply(do_this)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/514027.html
標籤:Python熊猫
