Home > Software design >  convert a list column to multiple columns based on a mapping dictionary in python
convert a list column to multiple columns based on a mapping dictionary in python

Time:09-27

Lets say I have a pandas dataframe with a column that contains a list:

d = {'id': ["First", "Second"], 'list_column': [[1,2,3], [3,2]]}
pd.DataFrame(data=d)

which looks like this:

| id       | list_column |
| -------- | ----------- |
| First    | [1, 2, 3]   |
| Second   | [3, 2]      |

and I also have a dictionary that maps the list values to a key, e.g.:

dict = {
  1: "red",
  2: "blue",
  3: "green"
}

How could I transform my list_column into multiple columns reflecting the contents of the list column, e.g.:

| id       | red | blue | green |
| -------- | --- | ---- | ----- |
| First    | 1   | 1    | 1     |
| Second   | 0   | 1    | 1     |

CodePudding user response:

You can first explode the column, then map the values using your dictionary, and use enter image description here

  • Related