首页 > 解决方案 > 切片包含 dic 值的 Pandas 列

问题描述

下面是我的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'}]

目的是用“Other_Name_name”、“Other_Name_language”、“Other_Name_type”替换“Other_Name”列

我遵循了以下帮助:Slice pandas dataframe json column into columns

此外,由于我有一些 NaN(我不想删除),因此该解决方案不起作用。

感谢任何人的帮助!

标签: pythonjsonpandas

解决方案


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)

推荐阅读