【问题标题】:How to flatten a Pandas dataframe json field that sometimes contains a list and sometimes a value如何展平有时包含列表和有时包含值的 Pandas 数据框 json 字段
【发布时间】:2019-07-05 17:25:44
【问题描述】:

我有一个 Pandas 数据框,其中包含一个我需要展平的 json 字段(并保留其余的数据框字段),令人困惑的部分是该字段有时(对于某些记录)包含一个列表,有时只有一个值(不在列表中)

例如(请运行sn-p查看数据框的示例):

<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>

我一直在尝试 Pandas 函数 json_normalize 但老实说文档很差而且示例很少,所以没有任何努力取得成功,任何建议都将不胜感激。

【问题讨论】:

  • 能否提供原始JSON?最好在解析时处理这个
  • 您的输入是第一个 HTML 而想要的输出是第二个 HTML?
  • 不,我使用 html 来举例说明数据框,但我认为它只会显示渲染的表格,而不是代码,我的输入是一个类似于第一个表格生成的数据框和期望的结果是一个类似于第二个表的数据框(请忽略我用来添加表的 html)

标签: python json pandas


【解决方案1】:

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

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

【讨论】:

  • 按预期工作!
猜你喜欢
  • 2016-03-16
  • 2016-11-29
  • 2019-10-24
  • 1970-01-01
  • 2023-02-20
  • 2021-12-03
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多