Blob
Blob

Reputation: 381

Merge two columns by mapping column names to row values of another column

Is it possible to merge two columns by mapping column names to values in antoher column?

df = pd.DataFrame(
    {
        "id": [1, 1, 2, 3],
        "label": ["foo", "moo", "foo", "moo"],
        "foo.foo": ["foo", "foo", "foo", np.nan],
        "moo.moo": ["moo", "moo", np.nan, np.nan],
    }
)

expected result:

id label foo.moo 
1  foo   foo     
1  moo   moo     
2  foo   foo 

Upvotes: 0

Views: 23

Answers (1)

sayan dasgupta
sayan dasgupta

Reputation: 1082

check if this works for you

df['foo_moo_updated'] = df['foo.moo'].mask(df.label=='foo',df['foo.foo'])
df[~df['foo_moo_updated'].isnull()]

    id  label   foo.foo foo.moo foo_moo_updated
0   1   foo foo moo foo
1   1   moo foo moo moo
2   2   foo foo NaN foo

Upvotes: 1

Related Questions