Warm tip: This article is reproduced from serverfault.com, please click

Apply Lambda on 2 dataframe columns in one line

发布于 2020-11-28 17:10:09
r_c = 'newyork sanfrancisco losangeles'.split()

def my_is_r_c(c):
    return c.replace(' ', '').lower() in r_c

train['is_r_c'] = train['c_o'].apply(lambda x: 1 if my_is_r_c(x) else 0)
train['is_r_c'] = train['c_d'].apply(lambda x: 1 if my_is_r_c(x) else 0)

Hi guys

Is there a way to apply the lambda for both columns ['c_o'] and ['c_d'], in only one line?

thx in advance

Questioner
laminado
Viewed
0
jottbe 2020-11-29 01:53:33

You could do that useing applymap like this:

df[['is_r_c', 'is_r_d']]= df[['c_o', 'c_d']].applymap(lambda x: 1 if my_is_r_c(x) else 0)

In case you want the columns combined, and there in fact is only one result column, which should contain 1 if your function evaluates to 1 for at least one of the columns, you can do that with a small variation like this:

df[['is_r_c']]= df[['c_o', 'c_d']].applymap(lambda x: 1 if my_is_r_c(x) else 0).max(axis='columns')