如何展平有时包含列表有时包含值的dataframe json字段

2024-04-27 00:39:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Pandas dataframe,其中包含一个json字段,我需要将其展平(并保留其余的dataframe字段),令人困惑的是,这个字段有时(对于某些记录)包含一个列表,有时仅包含一个值(不在列表中)

例如(请运行代码段以查看数据帧的示例):

<table> <th>rank</th> <th>Protocol</th> <th>Type</th> <tr> <td>1</td> <td>https</td> <td>{'ResultType': 'regular'}</td> </tr> <tr> <td>2</td> <td>https</td> <td>{'ResultType': ['amp', 'regular']}</td> </tr> </table>

期望的结果是:

<table> <th>rank</th> <th>Protocol</th> <th>Type</th> <tr> <td>1</td> <td>https</td> <td>regular</td> </tr> <tr> <td>2</td> <td>https</td> <td>amp</td> <tr> <td>2</td> <td>https</td> <td>regular</td> </tr> </table>

我一直在尝试熊猫函数jsonïu规范化,但老实说,文件是穷人和很少的例子,所以没有一个梅的努力是成功的,任何建议将不胜感激。你知道吗


Tags: httpsjsondataframepandas列表typetableprotocol
1条回答
网友
1楼 · 发布于 2024-04-27 00:39:31

您可以尝试以下解决方案:

In [10]: columns = ['rank','Protocol','Type']

In [11]: data=np.array([[1,'https',{'ResultType':'regular'}],[2,'https',{'ResultType':['amp','regular']}]])

In [12]: df = pd.DataFrame(data, columns=columns)

In [13]: df
Out[13]:
  rank Protocol                                   Type
0    1    https            {u'ResultType': u'regular'}
1    2    https  {u'ResultType': [u'amp', u'regular']}

In [14]: df['Type'] = df['Type'].apply(pd.Series)

In [15]: df2=df.set_index(['rank', 'Protocol'])['Type'].apply(pd.Series).stack()

In [16]: df2.name='Type'

In [17]: df2.reset_index()[columns]
Out[17]:
   rank Protocol     Type
0     1    https  regular
1     2    https      amp
2     2    https  regular

相关问题 更多 >