angie866
angie866

Reputation: 85

Map column of dataframe with different dictionaries

I have a dataframe df with two columns.

The 'data' column has some values, such as:

df['data'] = [0, 1, 0, 1]

The 'Dict' column has multiple dictionary, such as:

df['Dict'] = [{0: ['IPM_0'], 1: ['IPM_1']},
              {0: ['SPM_0'], 1: ['SPM_1']},
              {0: ['NPM_0'], 1: ['NPM_1']},
              {0: ['DPM_0'], 1: ['DPM_1']}]

Now I want to map each 'data'with the relative dictionary in 'Dict', such as that the result looks like:

df['result'] = [IPM_0, SPM_1, NPM_0, DPM_1]

I tried to use df['result'] = df.data.map(df.Dict) but I get a column with the same values as in df.Dict.

I tried also df['result'] = df.data.apply(lambda rows: rows.map(rows.Dict)) but I get an error 'int' object has no attribute 'map'

How can I achieve the result?

starting point:

   data                          Dict
0     0  {0: ['IPM_0'], 1: ['IPM_1']}
1     1  {0: ['SPM_0'], 1: ['SPM_1']}
2     0  {0: ['NPM_0'], 1: ['NPM_1']}
3     1  {0: ['DPM_0'], 1: ['DPM_1']}

ending point:

   data                          Dict result
0     0  {0: ['IPM_0'], 1: ['IPM_1']}  IPM_0
1     1  {0: ['SPM_0'], 1: ['SPM_1']}  SPM_1
2     0  {0: ['NPM_0'], 1: ['NPM_1']}  NPM_0
3     1  {0: ['DPM_0'], 1: ['DPM_1']}  DPM_1

Upvotes: 1

Views: 221

Answers (2)

mozway
mozway

Reputation: 260640

You can use apply. Keep in mind that storing complex structures in dataframes is not efficient!

df['result'] = df.apply(lambda r: r['Dict'][r['data']], axis=1)

output:

   data                          Dict   result
0     0  {0: ['IPM_0'], 1: ['IPM_1']}  [IPM_0]
1     1  {0: ['SPM_0'], 1: ['SPM_1']}  [SPM_1]
2     0  {0: ['NPM_0'], 1: ['NPM_1']}  [NPM_0]
3     1  {0: ['DPM_0'], 1: ['DPM_1']}  [DPM_1]

and if you want the first item of the list:

df['result'] = df.apply(lambda r: r['Dict'][r['data']][0], axis=1)

output:

   data                          Dict result
0     0  {0: ['IPM_0'], 1: ['IPM_1']}  IPM_0
1     1  {0: ['SPM_0'], 1: ['SPM_1']}  SPM_1
2     0  {0: ['NPM_0'], 1: ['NPM_1']}  NPM_0
3     1  {0: ['DPM_0'], 1: ['DPM_1']}  DPM_1

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71580

List comprehensions are always handy:

df['result'] = [x[y][0] for x, y in zip(df['Dict'], df['data'])]

Upvotes: 1

Related Questions