【发布时间】:2022-01-18 15:45:33
【问题描述】:
我有一个数据框,其中 2 列是我想扩展为单独列的字典列表。例如:
id text agg_inds agg_tars
1 some text [{"f1": [15], "f2": "2263"}, {"f1": [16], "f2": "2171"}] [{"f1": [5, 6, 12], "f2": "2984"}]
我想为名为 agg_inds 和 ind_id 的嵌套列 agg_inds 创建 2 个列,并为名为 tar_pos 和 tar_id 的 agg_tars 创建 2 个不同的列。
使用 json_normalize 的问题是当一个值重复时它返回 NaN 值。例如,在上面的行中,我想要这个:
期望的输出
id text ind_pos ind_id tar_pos tar_ind
1 [15] 2263 [5, 6, 12] 2984
1 some text [16] 2171 [5, 6, 12] 2984
但这是当前输出:
id tex ind_pos ind_id tar_pos tar_ind
1 [15] 2263 [5, 6, 12] 2984
1 NaN [16] 2171 NaN NaN
代码如下:
s = (df.set_index('id')
.apply(lambda x: x.apply(pd.Series).stack())
.reset_index()
.drop('level_1', 1))
s_ind = pd.json_normalize(s['agg_inds'])
columns_renaming = {"f1": "ind_pos", "f2": "ind_id"}
s_ind.rename(columns=columns_renaming, inplace=True)
s_tar= pd.json_normalize(s['agg_targets'])
columns_renaming = {"f1": "tar_pos", "f2": "tar_id"}
s_tar.rename(columns=columns_renaming, inplace=True)
s = s.drop(columns=['agg_inds', 'agg_targets'])
df_1 = s.join(s_ind)
df_final = df_1.join(s_tar)
print(df_final)
【问题讨论】:
标签: python pandas explode json-normalize