Python 熊猫系列中的JSON对象

Python 熊猫系列中的JSON对象,python,Python,我有一个pandas系列,其中列出了字符串格式的JSON对象作为值。下面是一个例子 sr = pd.Series(['[{"fruit": "apple", "box_a": 2}, {"fruit": "grape", "box_b": 4}]', '[{"fruit": "orange", "box_g": 2}]', '[{"fruit": "mango", "box_c": 6}, {"fruit": "grape", "box_e": 3}]']) 我的目标是找到一种有效的方法,将此

我有一个pandas系列,其中列出了字符串格式的JSON对象作为值。下面是一个例子

sr = pd.Series(['[{"fruit": "apple", "box_a": 2}, {"fruit": "grape", "box_b": 4}]', '[{"fruit": "orange", "box_g": 2}]', '[{"fruit": "mango", "box_c": 6}, {"fruit": "grape", "box_e": 3}]'])
我的目标是找到一种有效的方法,将此系列转换为具有以下结构的数据帧。作为新手,我只能考虑使用嵌套循环进行转换,在嵌套循环中我遍历每一行和每一项

sr_df = pd.DataFrame({'fruit':['apple', 'grape', 'orange', 'mango', 'grape'], 'box':['box_a', 'box_b', 'box_g', 'box_c', 'box_e'], 'count':[2,4,2,6,3]})
我期待学习新方法。

您可以使用:

  • 首先将字符串转换为python字典列表
  • 在创建新数据框的列表中,将列
    水果
    设置为索引
  • 并通过
  • 用于整数转换
  • 将多索引转换为列并重命名列


使用
json
itertools.chain
可以得到如下结果:

import itertools
import json
import pandas as pd

data_json = ['[{"fruit": "apple", "box_a": 2}, {"fruit": "grape", "box_b": 4}]', '[{"fruit": "orange", "box_g": 2}]', '[{"fruit": "mango", "box_c": 6}, {"fruit": "grape", "box_e": 3}]']
data = (json.loads(i) for i in data_json)
data = itertools.chain.from_iterable(data)
df = pd.DataFrame.from_records(data)
然后您可以将
水果
设置为索引和
堆栈
以获得结果

result = df.set_index('fruit').stack().astype(int)
  box_a   box_b   box_c   box_e   box_g   fruit
0 2.0                 apple
1     4.0             grape
2                 2.0 orange
3         6.0         mango
4             3.0     grape
result = df.set_index('fruit').stack().astype(int)
apple box_a   2
grape box_b   4
orange    box_g   2
mango box_c   6
grape box_e   3