我有一个巨大的 CSV 文件(3.5GB,并且每天都在变大),其中包含正常值和一个名为“元数据”的列,其中包含嵌套的 JSON 值。我的脚本如下所示,目的只是将 JSON 列转换为每个键值对的普通列。我正在使用 Python3(Anaconda;Windows)。
import pandas as pd
import numpy as np
import csv
import datetime as dt
from pandas.io.json import json_normalize
for df in pd.read_csv("source.csv", engine='c',
dayfirst=True,
encoding='utf-8',
header=0,
nrows=10,
chunksize=2,
converters={'Metadata':json.loads}):
## parsing code comes here
with open("output.csv", 'a', encoding='utf-8') as ofile:
df.to_csv(ofile, index=False, encoding='utf-8')
并且该列具有以下格式的 JSON:
{
"content_id":"xxxx",
"parental":"F",
"my_custom_data":{
"GroupId":"NA",
"group":null,
"userGuid":"xxxxxxxxxxxxxx",
"deviceGuid":"xxxxxxxxxxxxx",
"connType":"WIFI",
"channelName":"VOD",
"assetId":"xxxxxxxxxxxxx",
"GroupName":"NA",
"playType":"VOD",
"appVersion":"2.1.0",
"userEnvironmentContext":"",
"vodEncode":"H.264",
"language":"English"
}
}
期望的输出是将上述所有键值对作为列。数据框将包含其他非 JSON 列,我需要向其中添加从上述 JSON 解析的列。我尝试了 json_normalize,但我不确定如何将 json_normalize 应用于 Series 对象,然后将其转换(或分解)为多列。
请您参考如下方法:
直接对系列使用json_normalize(),然后使用pandas.concat()将新数据框与现有数据框合并:
pd.concat([df, json_normalize(df['Metadata'])])
如果您不再需要其中包含 JSON 数据结构的旧列,您可以添加 .drop('Metadata', axis=1)。
为 my_custom_data 嵌套字典生成的列将带有 my_custom_data. 前缀。如果嵌套字典中 中的所有名称都是唯一的,您可以使用DataFrame.rename() operation 删除该前缀。 :
json_normalize(df['Metadata']).rename(
columns=lambda n: n[15:] if n.startswith('my_custom_data.') else n)
如果您正在使用一些其他方法将每个字典值转换为扁平结构(例如,使用 flatten_json ,那么您想要使用 Series.apply() 来处理每个值,然后将每个生成的字典作为 pandas.Series() 对象返回:
def some_conversion_function(dictionary):
result = something_that_processes_dictionary_into_a_flat_dict(dictionary)
return pd.Series(something_that_processes_dictionary_into_a_flat_dict)
然后您可以将 Series.apply() 调用的结果(这将是一个数据帧)连接回您的原始数据帧:
pd.concat([df, df['Metadata'].apply(some_conversion_function)])
