python - pandas读取json格式数据

标签 python arrays json pandas

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

整个数据框看起来像

enter image description here

“customDimensions”列是 json 列,数据如下

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

我想将列展平为以下两列 自定义维度.index,自定义维度.value

我该怎么做?

最佳答案

您可以使用列表理解与 ast.literal_eval 来转换为字典列表, DataFrame.pop用于提取列和最后 DataFrame.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'])

关于python - pandas读取json格式数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55528646/

相关文章:

c++ - 读取数组末尾 : running in terminal vs. 调试器

javascript - 使用 NodeJS 在 JSON 文件中添加新的键值

json - Angular 6 错误处理 - HttpErrorResponse 具有未定义状态

Python类定义--导入语句

python - INFO menuinst_win32 :__init__(182): Menu: name: 'Anaconda${PY_VER} ${PLATFORM}'

java - 我的 stack 类中的 push() 会改变堆栈中的每个元素

c++ - C++ 中的字符数组验证

python - 我怎样才能调试这个Python代码?

Python数学抽认卡程序

arrays - 如何从另一个数组中的多个元素中选择数组中的元素