【发布时间】:2018-11-28 20:03:52
【问题描述】:
我正在尝试从包含列表的 json 中提取一个字段,然后将该列表附加到数据框,但我遇到了一些不同的错误。
我想我可以将它写入 csv,然后用 Pandas 读取 csv,但我试图避免写入任何文件。我知道我也可以使用 StringIO 来制作 csv,但这有空字节的问题。替换那些将是(我认为)另一个逐行步骤,这将进一步延长脚本完成所需的时间......我正在针对返回数千个结果的查询运行它,因此保持快速和简单优先考虑
首先我尝试了这个:
hit_json = json.loads(hit)
for ln in hit_json.get('hits').get('hits'):
df = df.append(ln['_source'], ignore_index=True)
print(df)
这给了我一个看起来像这样的结果:
1 2 3 4
a b d,e,f... x
然后我尝试了这个:
df = df.append(ln['_source']['payload'], ignore_index=True)
但这给了我这个错误:
TypeError: cannot concatenate object of type "<class 'str'>"; only pd.Series,
pd.DataFrame, and pd.Panel (deprecated) objs are valid
我正在寻找的是这样的:
0 1 2 3 4
d e f g h
除此之外...我需要找到一种方法来处理此列表中包含逗号的特定字符串...这可能是一个令人头疼的问题,最好在另一个问题中处理...例如:
# Obviously this is incorrect but I think you get the idea :)
str.replace(',', '^')
except if ',' followed by ' '
非常感谢任何帮助!
编辑以按要求添加 JSON
{
"_index": "sanitized",
"_type": "sanitized",
"_id": "sanitized".,
"_score": sanitized,
"_source": {
"sanitized": sanitized,
"sanitized": "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,\"34,35\",36,37,38,39,40",
"sanitized": "sanitized",
"sanitized": ["sanitized"],
"sanitized": "sanitized",
"sanitized": "sanitized",
"sanitized": "sanitized",
"sanitized": "sanitized",
}
}]
}
}
【问题讨论】:
-
请显示 JSON
-
Json 按要求添加
-
仍然不清楚:在这个 JSON 中看不到“命中”
标签: python list pandas dictionary