在Pandas数据框中使用JSON数据规范化列

问题描述

我有一个Pandas数据框,其中一列包含JSON数据(JSON结构很简单:只有一层,没有嵌套数据):

ID,Date,attributes
9001,2020-07-01T00:00:06Z,"{"State":"FL","Source":"Android","Request":"0.001"}"
9002,2020-07-01T00:00:33Z,"{"State":"NY","Request":"0.001"}"
9003,2020-07-01T00:07:19Z,"Source":"ios","Request":"0.001"}"
9004,2020-07-01T00:11:30Z,"Source":"windows","Request":"0.001"}"
9005,2020-07-01T00:15:23Z,"Request":"0.001"}"

My Pandas dataframe

我想规范属性列中的JSON内容,以便JSON属性成为数据框中的每一列。

ID,attributes.State,attributes.Source,attributes.Request
9001,FL,Android,0.001
9002,NY,0.001
9003,ios,0.001
9004,windows,0.001
9005,0.001 

我一直在尝试使用需要字典的Pandas json_normalize。因此,我想将 attributes 列转换为字典,但是对于字典的形式,它并不能按预期工作:

df.attributes.to_dict()

{0: '{"State":"FL","Request":"0.001"}',1: '{"State":"NY",2: '{"State":"FL",3: '{"State":"NY",4: '{"State":"FL","Request":"0.001"}'}

并且规范化将键(0、1、2,...)作为列名,而不是JSON键。

我感觉自己很亲近,但我还不太想清楚如何精确地做到这一点。任何想法都欢迎。

谢谢!

解决方法

您不需要先转换为词典。

尝试:

import pandas as pd

pd.json_normalize(df[‘attributes’])
,

Normalize 期望处理一个对象,而不是一个字符串。

import json
import pandas as pd
df_final = pd.json_normalize(df.attributes.apply(json.loads))
,

我找到了解决方案,但我对此不太满意。我认为这是非常无效的。

import pandas as pd
import json

# Import full dataframe
df = pd.read_csv(r'D:/tmp/sample_simple.csv',parse_dates=['Date'])

# Create empty dataframe to hold the results of data conversion
df_attributes = pd.DataFrame()

# Loop through the data to fill the dataframe
for index in df.index:
    row_json = json.loads(df.attributes[index])
    normalized_row = pd.json_normalize(row_json)
    df_attributes = df_attributes.append(normalized_row)

# Reset the index of the attributes dataframe
df_attributes = df_attributes.reset_index(drop=True)

# Drop the original attributes column
df = df.drop(columns=['attributes'])

# Join the results
df_final = df.join(df_attributes)

# Show results
print(df_final)
print(df_final.info())

这给了我预期的结果。但是,正如我所说,它有几个不足之处。对于初学者,数据框将附加在 for循环中。根据文档,最佳实践是制作一个列表,然后追加,但是在保持所需形状的同时我不知道该怎么做。我欢迎所有批评家和想法。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...