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,541
  • 28
  • 38
  • 38
A2N15
  • 595
  • 4
  • 20

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
  • 4,079
  • 1
  • 13
  • 27
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,594
  • 1
  • 6
  • 9