如何在Panda中连接多个JSON列

klr1opcd  于 2022-09-21  发布在  其他
关注(0)|答案(2)|浏览(143)

我有一个如下格式的df:

  1. id json_1 json_2 json_3
  2. 1 {a:b} {a:c} {c:d}
  3. 2 {a:b} {b:c} null
  4. 3 {a:c} {c:d} {a:g}

我想创建一个新列,将json_1、json_2和json_3列连接起来(即使用联合)。

所需输出:

  1. id json_1 json_2 json_3 final_json
  2. 1 {a:b} {a:c} {c:d} {{a:b}, {a:c}, {c:d}}
  3. 2 {a:b} {b:c} null {{a:b}, {b:c}}
  4. 3 {a:c} {c:d} {a:g} {{a:c}, {c:d}, {a:g}}
1szpjjfi

1szpjjfi1#

IIUC使用:

  1. df['final_json'] = df.filter(like='json').apply(lambda x: [y for y in x if pd.notna(y)], axis=1)
7dl7o3gd

7dl7o3gd2#

根据数据类型和其他要求,这项工作应已完成

  1. df['final_json'] = df[['json_1', 'json_2', 'json_3']].apply(lambda x: set(x) - set(['null']), axis=1)
  2. [Out]:
  3. id json_1 json_2 json_3 final_json
  4. 0 1 {a:b} {a:c} {c:d} {{c:d}, {a:c}, {a:b}}
  5. 1 2 {a:b} {b:c} null {{b:c}, {a:b}}
  6. 2 3 {a:c} {c:d} {a:g} {{a:g}, {c:d}, {a:c}}

相关问题