Home > Back-end >  Pandas mapping a column: Is it possible for the map function to return a dictionary for automatic co
Pandas mapping a column: Is it possible for the map function to return a dictionary for automatic co

Time:07-09

Say that I have a pandas example column

df
a
1
2
3
4

Is it possible to map the column using a function that returns a dictionary, such that the dictionary keys are used for the column assignment?

Continuing with the example

The mapping function

def red(x):
   return {'b': x 1, 'c': x 2}

And the final result would be

df
a b c 
1 2 3
2 3 4
3 4 5
4 5 6

which would be achievable programmatically in python/pandas somehow

df = df.magic_map(red)

CodePudding user response:

Can you do the following?:

def red(x):
   b = x   1
   c = x   2
   return pd.Series([b, c], index=['b', 'c'])

df = df['a'].apply(red)

Or this one is shorter:

df = df['a'].apply(lambda x: pd.Series([x 1, x 2], index=['b', 'c']))

CodePudding user response:

Yes, you can:

a = pd.DataFrame([[1], [2]])

def func(v):
    return {1: v   1, 2: v   2}

a[0].map(func).apply(pd.Series)

And if they overlap with th existing ones then

new_cols = a[0].map(func).apply(pd.Series)
a.update(new_cols)

will rewrite the existing values if they appear in new_cols.

Also I personally think this manner is implicit. So if you can, it is better to use something like this:

def update_df(df: pd.DataFrame) -> None:
    df['x1'] = df['x']   1
    df['x2'] = df['x']   2
  • Related