![](/img/trans.png)
[英]Apply a function to two DataFrame columns and create new column from result
[英]How to apply if condition to two different columns and put the result to a new column
我有一個數據框df2
,並希望根據兩個現有列的if
邏輯生成一個名為“標簽”的新列。
import pandas as pd
df2 = pd.DataFrame({'NOTES': ["PREPAID_HOME_SCREEN_MAMO","SCREEN_MAMO",
"> Unable to connect internet>4G Compatible>Set",
"No>Not Barred>Active>No>Available>Others>",
"Internet Not Working>>>Unable To Connect To"],
'col_1': ["voice", "voice","data","other","voice"],
'col_2': ["DATA", "voice","VOICE","VOICE","voice"]})
邏輯和我的嘗試是:
df2['Tag'] =
if df['col_1']=='data':
return "Yes"
elif df['col_2']:
return "Yes"
else:
return "No"
問題是您試圖用 if-語句賦值,這會導致語法錯誤。
有很多方法可以做到這一點,我提供了一種使用pandas.DataFrame.apply
的方法。
trans_fn = lambda row: "Yes" if row['col_1']=='data' && row['col_2'] else "No"
df2['tag'] = df2.apply(trans_fn, axis=1) # apply trans_fn to each row
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.