Python 展平json以获得多个列

Python 展平json以获得多个列,python,pandas,Python,Pandas,我有一个示例数据帧 sample_df = pd.DataFrame({'id': [1, 2], 'fruits' :[ [{'name': u'mango', 'cost': 100, 'color': u'yellow', 'size': 12}], [{'name': u'mango', 'cost': 150, 'color': u'yellow', 'size': 21}, {'name': u'banana', 'cost': 200, 'color':

我有一个示例数据帧

sample_df = pd.DataFrame({'id': [1, 2], 'fruits' :[
    [{'name': u'mango', 'cost': 100, 'color': u'yellow', 'size': 12}],
    [{'name': u'mango', 'cost': 150, 'color': u'yellow', 'size': 21},
     {'name': u'banana', 'cost': 200, 'color': u'green', 'size': 10} ]
]})
我想展平
水果
列,以获得新列,如
名称、成本、颜色
大小
。一个
id
可以有多个水果条目。例如,
ID2
有两种水果的信息
mango
banana

print(sample_df)

                                              fruits  id
0  [{'name': 'mango', 'cost': 100, 'color': 'yell...   1
1  [{'name': 'mango', 'cost': 150, 'color': 'yell...   2
在输出中,我希望有3条记录,1条记录带有
ID1
的水果信息,2条记录带有
ID2

有没有办法使用pandas解析此结构?

首先是列,然后是
concat
调用
DataFrame

s=unnesting(sample_df,['fruits']).reset_index(drop=True)

df=pd.concat([s.drop('fruits',1),pd.DataFrame(s.fruits.tolist())],axis=1)
df
Out[149]: 
   id   color  cost    name  size
0   1  yellow   100   mango    12
1   2  yellow   150   mango    21
2   2   green   200  banana    10


方法2

sample_df.set_index('id').fruits.apply(pd.Series).stack().apply(pd.Series).reset_index(level=0)
Out[159]: 
   id   color  cost    name  size
0   1  yellow   100   mango    12
0   2  yellow   150   mango    21
1   2   green   200  banana    10

谢谢你的回答。当我将其应用于实际数据时,它会返回一个错误-
ValueError:零维数组无法连接。我不知道如何最好地解决这个问题。@Regressor filter在运行
untesting
sample\u df=sample\u df[sample\u df.fruits.astype(bool)].copy()之前进行过滤。
@Regressor好的,让我们试试另一种方法,我会更新,让我在实际数据集上尝试运行新方法。当我在实际数据集上尝试其他方法时,它按原样返回
id
和json。
sample_df.set_index('id').fruits.apply(pd.Series).stack().apply(pd.Series).reset_index(level=0)
Out[159]: 
   id   color  cost    name  size
0   1  yellow   100   mango    12
0   2  yellow   150   mango    21
1   2   green   200  banana    10