2015-05-29 377 views

回答

13

一个选项列表与os.listdir目录下的所有文件,然后发现只有那些在“以.json”结尾:

import os, json 
import pandas as pd 

path_to_json = 'somedir/' 
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')] 
print(json_files) # for me this prints ['foo.json'] 

现在你可以使用熊猫DataFrame.from_dict在JSON(读一个Python字典在这一点上),以一个数据帧大熊猫:

montreal_json = pd.DataFrame.from_dict(many_jsons[0]) 
print montreal_json['features'][0]['geometry'] 

打印:

{u'type': u'Point', u'coordinates': [-73.6051013, 45.5115944]} 

在这种情况下,我将一些jsons附加到列表many_jsons。我列表中的第一个json实际上是一个geojson,其中包含蒙特利尔的一些地理数据。我已经熟悉了这些内容,因此我打印出了“几何图形”,它给了我蒙特利尔的长/短。

下面的代码概括了一切之上:

import os, json 
import pandas as pd 

# this finds our json files 
path_to_json = 'json/' 
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')] 

# here I define my pandas Dataframe with the columns I want to get from the json 
jsons_data = pd.DataFrame(columns=['country', 'city', 'long/lat']) 

# we need both the json and an index number so use enumerate() 
for index, js in enumerate(json_files): 
    with open(os.path.join(path_to_json, js)) as json_file: 
     json_text = json.load(json_file) 

     # here you need to know the layout of your json and each json has to have 
     # the same structure (obviously not the structure I have here) 
     country = json_text['features'][0]['properties']['country'] 
     city = json_text['features'][0]['properties']['name'] 
     lonlat = json_text['features'][0]['geometry']['coordinates'] 
     # here I push a list of data into a pandas DataFrame at row given by 'index' 
     jsons_data.loc[index] = [country, city, lonlat] 

# now that we have the pertinent json data in our DataFrame let's look at it 
print(jsons_data) 

对于我这种打印:

country   city     long/lat 
0 Canada Montreal city [-73.6051013, 45.5115944] 
1 Canada  Toronto [-79.3849008, 43.6529206] 

这可能是让你知道,这个代码,我在一个目录名有两个geojsons“ JSON”。每个json的结构如下:

{"features": 
[{"properties": 
{"osm_key":"boundary","extent": 
[-73.9729016,45.7047897,-73.4734865,45.4100756], 
"name":"Montreal city","state":"Quebec","osm_id":1634158, 
"osm_type":"R","osm_value":"administrative","country":"Canada"}, 
"type":"Feature","geometry": 
{"type":"Point","coordinates": 
[-73.6051013,45.5115944]}}], 
"type":"FeatureCollection"} 
+0

真的很有帮助。而不是打印我的想法是将它们全部保存到一个熊猫数据框中,应该是什么样的正确的代码?创建一个空的数据框并开始向它添加行?谢谢@Scott这个详细的答案! – donpresente

+1

@donpresente好问题。我将发布一个编辑来解决如何从json获取所需的数据,然后逐行将这些数据推送到熊猫数据框中。 – Scott

+1

@donpresente在** EDIT **下面执行了代码帮助你? – Scott

1

要读取JSON文件,

import os 
import glob 

contents = [] 
json_dir_name = "/path/to/json/dir" 

json_pattern = os.path.join(json_dir_name,'*.json' 
file_list = glob.glob(json_pattern) 
for file in file_list: 
    contents.append(read(file)) 
+0

contents.append正在创建一个字典,将所有已获得的json文件添加到它中?谢谢@Saravana! – donpresente

+1

'contents.append'将一个元素添加到列表'contents'中。 –

+0

“* .json”后面应该有逗号)“ –

6

一个迭代(平坦)的目录是容易与glob模块

from glob import glob 

for f_name in glob('foo/*.json'): 
    ... 

至于读取JSON直接进入pandas,见here

+0

直接链接https://hayd.github.io/2013/pandas-json –