I have a pyspark dataframe like the following:
| id | tmp_list | other features |
|---|---|---|
| 1 | ['Spain', 'Italy'] | xxx |
| 2 | ['Spain', 'France', 'USA', 'India'] | yyy |
| 3 | ['Spain', 'Germany'] | zzz |
and a list of countries like the following:
EU_countries = ['Spain', 'Italy', 'France', 'Germany']
I want to do the following:
- Extract all unique values from the column
tmp_list - Create new columns for all the values present in
EU_countries. For the values that don't exist inEU_countries, create a column calledother_countries. Essentially, create column for every entry inEU_countrieslist + an extra column calledother_countries. - If an
idcontains any of the countries from theEU_countrieslist, the new columnSpainshould have1as value else0. Same applies to the other countries fromEU_countrieslist. - If an
idcontains any country that doesn't exist in theEU_countrieslist,other_countriescolumn should be filled1else0.
This is the final output I am looking for:
| id | Spain | Italy | France | Germany | other_countries | other features |
|---|---|---|---|---|---|---|
| 1 | 1 | 1 | 0 | 0 | 0 | xxx |
| 2 | 1 | 0 | 1 | 0 | 1 | yyy |
| 3 | 1 | 0 | 0 | 1 | 0 | zzz |
I am breaking my head over this. Can somebody please help me with this?
Any help is greatly appreciated! Thank you so much!