我有一个 csv 文件,其中一列是 json。我希望能够访问 json 列中的信息,但我无法弄清楚。
我的csv文件是这样的
id, "letter", "json"
1,"a","{""add"": 2}"
2,"b","{""sub"": 5}"
3,"c","{""add"": {""sub"": 4}}"
我正在看书,喜欢喜欢
test = pd.read_csv(filename)
df = pd.DataFrame(test)
我希望能够获取 json 列中具有“sub”的所有行,并最终能够获取这些键的值。
最佳答案
这是一种方法,它使用 read_csv
converters
参数将 json
构建为 JSON。然后使用 apply
选择每行中的 json
字段键。 CustomParser
取自 this answer .
编辑
更新为看起来有两层深度,并采用可变的 target
参数(因此它可以根据需要“添加”或“子”)。不过,此解决方案无法处理任意数量的关卡。
def CustomParser(data):
import json
j1 = json.loads(data)
return j1
df = pd.read_csv('test.csv', converters={'json':CustomParser})
def check_keys(json, target):
if target in json:
return True
for key in json:
if isinstance(json[key], dict):
if target in json[key]:
return True
return False
print(df.loc[df.json.apply(check_keys, args=('sub',))])
id letter json
1 2 b {'sub': 5}
2 3 c {'add': {'sub': 4}}
关于python - 使用 pandas 访问 json 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43668533/