【问题标题】:Pandas read json format dataPandas读取json格式数据
【发布时间】:2019-08-26 23:01:42
【问题描述】:

我在一个数据框中有一个 json 列。

整个数据框看起来像

“customDimensions”列是json列,数据是这样的

[{'index': '4', 'value': 'North America'}]

我想将该列展平为以下 2 列 customDimensions.index、customDimensions.value

我该怎么做?

【问题讨论】:

标签: python arrays json pandas


【解决方案1】:

您可以使用列表推导和ast.literal_eval 转换为dict 列表,DataFrame.pop 用于提取列,lastDataFrame.join 用于原始:

#if values are strings
print (type(df.loc[0,'customDimension']))
<class 'str'>

import ast

df1 = (pd.DataFrame([ast.literal_eval(x)[0] for x in df.pop('customDimension')])
         .add_prefix('customDimensions.'))

#if values are lists
print (type(df.loc[0,'customDimension']))
<class 'list'>


df = pd.DataFrame([x[0] for x in df.pop('customDimension')]).add_prefix('customDimensions.')

df = df.join(df1)

如果来源是json,最好使用json.json_normalize

#not tested, depends of json format and data
df = json_normalize(j, 'customDimension', ['channelGrouping','date'])

【讨论】:

  • 你也可以使用 apply。 def getCol(x,col): return x[col] df["customDimensions.index"] = df["customDimensions"].apply(lambda x:getCol(x,"index"))
  • 你太棒了!我的数据是,你的回答完美解决了我的问题!
猜你喜欢
  • 2019-06-09
  • 2012-11-10
  • 2019-12-05
  • 2021-10-30
  • 2017-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多