0

Below is my DF:

df = pd.DataFrame({'Name': ['AZ', 'AF'], 'Other_Name': [np.nan, [{'name': 'ARES ZAN', 'language': 'en', 'type': 'ALTERNATIVE'}]]})


Name    Other_Name
0   AZ  NaN
1   AF  [{'name': 'ARES ZAN', 'language': 'en', 'type': 'ALTERNATIVE'}]

The aim is to replace 'Other_Name' column with 'Other_Name_name', 'Other_Name_language', 'Other_Name_type'

I followed the help from: Slice pandas dataframe json column into columns

Besides, as I have some NaN (which I don't want to remove), the solution isn't working.

Thanks to anyone helping!

Jason Aller
  • 3,475
  • 28
  • 40
  • 37
A2N15
  • 552
  • 2
  • 13

2 Answers2

0
def change_key(x):
    for data_dict in x:
        for key in list(data_dict.keys()):
            data_dict[f'Other_Name_{key}'] = data_dict.pop(key)

    return x

df.loc[~df['Other_Name'].isnull(), 'Other_Name'] = df[~df['Other_Name'].isnull()]['Other_Name'].apply(change_key)
print(df)
Muhammad Hassan
  • 3,719
  • 1
  • 10
  • 24
0

You can do the following:

all_keys = ['name', 'language', 'type']
for key in all_keys:
  df.loc[df.Other_Name.notnull(), 'Other_Name_' + key] = df.loc[df.Other_Name.notnull(), 'Other_Name']\
                                                           .explode()\
                                                           .apply(lambda x: x[key])

Output:

    Other_Name_name     Other_Name_language     Other_Name_type
0   NaN                       NaN                  NaN
1   ARES ZAN                  en                  ALTERNATIVE
ashkangh
  • 1,556
  • 1
  • 5
  • 9