我在一个数据框中有一个json列。
整个数据框看起来像
“ customDimensions”列为json列,数据类似于
[{'index': '4', 'value': 'North America'}]
我想将列平整为以下2列 customDimensions.index,customDimensions.value
我该怎么做?
答案 0 :(得分:2)
您可以对print(message['message']['params']['response']['url'])
使用列表推导来转换为字典列表,DataFrame.pop
用于提取列,最后DataFrame.join
为原始列表:
ast.literal_eval
#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_normalize
。
json