【发布时间】:2015-08-12 21:59:31
【问题描述】:
我想知道如何从一个文件夹中读取多个json 文件(不指定文件名,只是它们是 json 文件)。
另外,是否可以将它们变成pandas DataFrame?
你能给我一个基本的例子吗?
【问题讨论】:
我想知道如何从一个文件夹中读取多个json 文件(不指定文件名,只是它们是 json 文件)。
另外,是否可以将它们变成pandas DataFrame?
你能给我一个基本的例子吗?
【问题讨论】:
一种选择是列出带有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']
现在您可以使用 pandas DataFrame.from_dict 将 json(此时为 python 字典)读入 pandas 数据帧:
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]}
在这种情况下,我将一些 json 附加到列表 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]
知道对于此代码,我在目录名称“json”中有两个 geojson 可能会有所帮助。每个 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"}
【讨论】:
将所有以 * .json 结尾的文件从特定目录加载到字典中:
import os,json
path_to_json = '/lala/'
for file_name in [file for file in os.listdir(path_to_json) if file.endswith('.json')]:
with open(path_to_json + file_name) as json_file:
data = json.load(json_file)
print(data)
自己试试吧: https://repl.it/@SmaMa/loadjsonfilesfromfolderintodict
【讨论】:
要读取 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))
【讨论】:
contents.append 向列表中添加一个元素contents。
如果要转换成 pandas 数据框,请使用 pandas API。
更一般地说,您可以使用生成器..
def data_generator(my_path_regex):
for filename in glob.glob(my_path_regex):
for json_line in open(filename, 'r'):
yield json.loads(json_line)
my_arr = [_json for _json in data_generator(my_path_regex)]
【讨论】:
我觉得缺少使用 pathlib 的解决方案 :)
from pathlib import Path
file_list = list(Path("/path/to/json/dir").glob("*.json"))
【讨论】:
另一种选择是将其作为 PySpark Dataframe 读取,然后将其转换为 Pandas Dataframe(如果真的有必要,取决于我建议保留为 PySpark DF 的操作)。 Spark 原生处理使用带有 JSON 文件的目录作为主路径,而不需要库来读取或迭代每个文件:
# pip install pyspark
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
spark_df = spark.read.json('/some_dir_with_json/*.json')
接下来,为了转换成 Pandas Dataframe,你可以这样做:
df = spark_df.toPandas()
【讨论】:
我正在使用glob 和pandas。查看以下代码
import pandas as pd
from glob import glob
df = pd.concat([pd.read_json(f_name, lines=True) for f_name in glob('foo/*.json')])
【讨论】: