我在一个数据帧中有一个 json 列。
整个数据框看起来像
“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/