【发布时间】:2017-07-07 17:24:09
【问题描述】:
我已将嵌套的 JSON 文件转换为 pandas DataFrame。一些列现在包含列表。它们看起来像这样:
0 [BikeParking: True, BusinessAcceptsBitcoin: Fa...
1 [BusinessAcceptsBitcoin: False, BusinessAccept...
2 [Alcohol: none, Ambience: {'romantic': False, ...
3 [AcceptsInsurance: False, BusinessAcceptsCredi...
4 [BusinessAcceptsCreditCards: True, Restaurants...
5 [BusinessAcceptsCreditCards: True, ByAppointme...
6 [BikeParking: True, BusinessAcceptsCreditCards...
7 [Alcohol: none, Ambience: {'romantic': False, ...
8 [BusinessAcceptsCreditCards: True]
9 [BikeParking: True, BusinessAcceptsCreditCards...
10 None
.
.
.
144070 [Alcohol: none, Ambience: {'romantic': False, ...
144071 [BikeParking: True, BusinessAcceptsCreditCards...
Name: attributes, dtype: object
还有这个:
0 [Monday 11:0-21:0, Tuesday 11:0-21:0, Wednesda...
1 [Monday 0:0-0:0, Tuesday 0:0-0:0, Wednesday 0:...
2 [Monday 11:0-2:0, Tuesday 11:0-2:0, Wednesday ...
3 [Tuesday 10:0-21:0, Wednesday 10:0-21:0, Thurs...
4 None
144066 None
144067 [Tuesday 8:0-16:0, Wednesday 8:0-16:0, Thursda...
144068 [Tuesday 10:0-17:30, Wednesday 10:0-17:30, Thu...
144069 None
144070 [Monday 11:0-20:0, Tuesday 11:0-20:0, Wednesda...
144071 [Monday 10:0-21:0, Tuesday 10:0-21:0, Wednesda...
Name: hours, dtype: object
我有什么方法可以自动提取标签(BikeParking、AcceptsInsurance 等)并将它们用作列名,同时用真/假值填充单元格。对于 Ambience dict,我想在单元格中执行 Ambience_romantic 和 true/false 之类的操作。同样,我想将星期几提取为列名,并使用小时来填充单元格。
或者之前有没有办法将json数据展平?我尝试将 json 数据逐行传递给 json_normalize 并从输出中创建一个数据框,但它会产生相同的结果。也许我做错了什么?
原始json格式(yelp_academic_dataset_business.json):
{
"business_id":"encrypted business id",
"name":"business name",
"neighborhood":"hood name",
"address":"full address",
"city":"city",
"state":"state -- if applicable --",
"postal code":"postal code",
"latitude":latitude,
"longitude":longitude,
"stars":star rating, rounded to half-stars,
"review_count":number of reviews,
"is_open":0/1 (closed/open),
"attributes":["an array of strings: each array element is an attribute"],
"categories":["an array of strings of business categories"],
"hours":["an array of strings of business hours"],
"type": "business"
}
我对 json_normalize 的初步尝试:
with open('yelp_academic_dataset_business.json') as f:
#Normalize the json data to flatten it and store output in a dataframe
frame= json_normalize([json.loads(line) for line in f])
#write the dataframe to a csv file
frame.to_csv('yelp_academic_dataset_business.csv', encoding='utf-8', index=False)
我目前正在尝试什么:
with open(json_filename) as f:
data = f.readlines()
# remove the trailing "\n" from each line
data = map(lambda x: x.rstrip(), data)
data_json_str = "[" + ','.join(data) + "]"
df = read_json(data_json_str)
#Now Looking to expand df['attributes'] and others here
我还应该提到我的目标是将其转换为 .csv 以将其加载到数据库中。我不想在我的数据库列中列出列表。
您可以从 Yelp 数据集挑战网站获取原始 json 数据: https://www.yelp.ca/dataset_challenge/dataset
【问题讨论】:
-
我们可以看看原始 json 和你的尝试吗?
-
添加了 json 格式、数据链接和我的尝试。
标签: python json list pandas dataframe