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
CodePudding user response:
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