我正在尝试从json数据下面获取嵌套值。
{
"region_id": 60763,
"phone": "",
"address": {
"region": "NY",
"street-address": "147 West 43rd Street",
"postal-code": "10036",
"locality": "New York City"
},
"id": 113317,
"name": "Casablanca Hotel Times Square"
}
{
"region_id": 32655,
"phone": "",
"address": {
"region": "CA",
"street-address": "300 S Doheny Dr",
"postal-code": "90048",
"locality": "Los Angeles"
},
"id": 76049,
"name": "Four Seasons Hotel Los Angeles at Beverly Hills"
}
我只是使用以下方法将上述数据加载到我的pandas数据框中:
with open("file path") as f:
df = pd.DataFrame(json.loads(line) for line in f)
现在我的数据框看起来像这样:
address Phone
0 {u'region': u'NY', u'street-address': u'147 We...
1 {u'region': u'CA', u'street-address': u'300 S ...
id name region_id
0 113317 Casablanca Hotel Times Square 60763
1 76049 Four Seasons Hotel Los Angeles at Beverly Hills 32655
我可以使用这个 - data = df[['id', 'name']]
但不确定我如何获得region
和street-address
以及id
和name
的值。我的输出数据框应该有id, name, region, street-address
。
注意:我尝试弹出并将此嵌套列address
与我的数据框连接起来。但是由于我的数据量很大--348MB,因此当我逐列扫描时,连接会占用大量内存 - (轴-1)。
此外,我正在寻找一种有效的方法来处理这个,我应该使用Numpy,它将直接使用C扩展。或者写入MongoDB等数据库。我正在考虑这个问题,因为在对这些数据进行子集化之后,我需要基于id列加入这个其他数据集以获得其他几个字段。
答案 0 :(得分:3)
以下方法可行(但是,我在下面添加了一个更有效的解决方案;只需向下滚动到编辑):
import pandas as pd
# read the updated json file
df = pd.read_json('data.json')
# convert column with the nested json structure
tempdf = pd.concat([pd.DataFrame.from_dict(item, orient='index').T for item in df.address])
# get rid of the converted column
df.drop('address', 1, inplace=True)
# prepare concat
tempdf.index = df.index
# merge the two dataframes back together
df = pd.concat([df, tempdf], axis=1)
输出:
id name phone region_id \
0 113317 Casablanca Hotel Times Square 60763
1 76049 Four Seasons Hotel Los Angeles at Beverly Hills 32655
region street-address postal-code locality
0 NY 147 West 43rd Street 10036 New York City
1 CA 300 S Doheny Dr 90048 Los Angeles
现在,您可以使用drop
命令删除不需要的列。
我修改了你实际上无效的json文件;你可以检查它,例如在JSONLint:
[{
"region_id": 60763,
"phone": "",
"address": {
"region": "NY",
"street-address": "147 West 43rd Street",
"postal-code": "10036",
"locality": "New York City"
},
"id": 113317,
"name": "Casablanca Hotel Times Square"
}, {
"region_id": 32655,
"phone": "",
"address": {
"region": "CA",
"street-address": "300 S Doheny Dr",
"postal-code": "90048",
"locality": "Los Angeles"
},
"id": 76049,
"name": "Four Seasons Hotel Los Angeles at Beverly Hills"
}]
修改强>
建立@ MaxU的答案(这对我不起作用),您还可以执行以下操作:
import pandas as pd
import ujson
from pandas.io.json import json_normalize
# this is the json file from above
with open('data.json') as f:
data = ujson.load(f)
现在,正如@MaxU所提议的,您可以使用json_normalize来摆脱嵌套结构:
df3 = json_normalize(data)
这会给你:
address.locality address.postal-code address.region address.street-address id name phone region_id
0 New York City 10036 NY 147 West 43rd Street 113317 Casablanca Hotel Times Square 60763
1 Los Angeles 90048 CA 300 S Doheny Dr 76049 Four Seasons Hotel Los Angeles at Beverly Hills 32655
您可以像这样重命名要保留的列:
df3.rename(columns={'address.region': 'region', 'address.street-address': 'street-address'}, inplace=True)
然后选择您要保留的列:
df3 = df3[['id', 'name', 'region', 'street-address']]
为您提供所需的输出:
id name region street-address
0 113317 Casablanca Hotel Times Square NY 147 West 43rd Street
1 76049 Four Seasons Hotel Los Angeles at Beverly Hills CA 300 S Doheny Dr
答案 1 :(得分:2)
小助手功能可以解决这个问题:
def get_entries(line):
data = json.loads(line)
res = {k: data[k] for k in ['id', 'name']}
res.update({k: data['address'][k] for k in ['region', 'street-address']})
return res
with open("file path") as f:
df = pd.DataFrame(get_entries(line) for line in f)
输出:
id name region \
0 113317 Casablanca Hotel Times Square NY
1 76049 Four Seasons Hotel Los Angeles at Beverly Hills CA
street-address
0 147 West 43rd Street
1 300 S Doheny Dr
或者,看起来好一点:
答案 2 :(得分:2)
原生熊猫解决方案 - pandas.io.json.json_normalize():
已更正且正常工作版本:
import ujson
import pandas as pd
from pandas.io.json import json_normalize
pd.set_option('display.expand_frame_repr', False)
with open('aaa') as f:
data = ujson.load(f)
df = json_normalize(data)[['id', 'name', 'address.region', 'address.street-address']].rename(columns={'address.region': 'region', 'address.street-address': 'street-address'})
print(df)
输出:
id name region street-address
0 113317 Casablanca Hotel Times Square NY 147 West 43rd Street
1 76049 Four Seasons Hotel Los Angeles at Beverly Hills CA 300 S Doheny Dr
NOT WORKING版本(正如Cleb指出的那样):
import ujson
from pandas.io.json import json_normalize
with open('data.json') as f:
data = ujson.load(f)
df = json_normalize(data, 'address', ['region', 'street-address'])
pd.set_option('display.expand_frame_repr', False)
print(df)
或者,你可以使用ujson
(超快速JSON)来生成字典列表,然后从中生成一个DataFrame:
import ujson
import pandas as pd
data_list = []
with open('data.json') as f:
for line in f:
d = ujson.loads(line)
data_list.append(
{"id":d["id"],
"name":d["name"],
"region":d["address"]["region"],
"street-address":d["address"]["street-address"]
}
)
df = pd.DataFrame(data_list)
pd.set_option('display.expand_frame_repr', False)
print(df)
我不知道哪种解决方案会更有效/更快 - 请尝试对付您的实际数据(348MiB)并给我们一个简短的反馈。
PS如果可能的话,只调用一次pd.DataFrame / pd.read_json,否则会慢得多。
输出:
id name region street-address
0 113317 Casablanca Hotel Times Square NY 147 West 43rd Street
1 76049 Four Seasons Hotel Los Angeles at Beverly Hills CA 300 S Doheny Dr
答案 3 :(得分:2)
首先,使用id
的{{1}}和name
列创建新的数据框。然后遍历每个目标字段(均位于df
)并应用address
函数从字典中获取项目。
lambda