pandas 如何将if条件应用于两个不同的列并将结果放入新列

brccelvz  于 2022-11-20  发布在  其他
关注(0)|答案(1)|浏览(154)

我有一个 Dataframe df2,希望基于两个现有列上的if逻辑生成一个名为“tag”的新列。

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"

但是我得到了一个语法错误:

zwghvu4y

zwghvu4y1#

问题是您试图使用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

相关问题