Python:从文件夹中读取多个json文件

2023-12-26

我想知道如何阅读几本json来自单个文件夹的文件(不指定文件名,只是它们是 json 文件)。

此外,还可以将它们变成pandas数据框?

你能给我一个基本的例子吗?


一种选择是列出目录中的所有文件操作系统列表目录 https://docs.python.org/2/library/os.html#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 http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.from_dict.html将 json(此时为 python 字典)读入 pandas 数据帧:

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

Prints:

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

在本例中,我已将一些 json 附加到列表中many_jsons。我列表中的第一个 json 实际上是geojson http://geojson.org/以及蒙特利尔的一些地理数据。我已经熟悉了内容,所以我打印了“几何图形”,它给了我蒙特利尔的经度/纬度。

以下代码总结了以上所有内容:

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"}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python:从文件夹中读取多个json文件 的相关文章

随机推荐

  • 如何使用 bash 脚本编辑 XML?

  • 使用 oauth 登录 Facebook 在实时服务器上失败

    我正在使用 OAuthWebSecurity 通过 facebook 登录 它正在本地主机上运行 但是 然后部署到实时服务器时 我收到以下错误消息 远程服务器返回错误 400 错误请求 我已检查 Facebook 上的域名详细信息是否正确
  • 如何确定 MySQL 5.1 中索引的大小?

    如何确定 MySQL 5 1 中索引的大小 is this http dev mysql com doc refman 5 1 en show table status html你需要什么 从这里 https stackoverflow c
  • postgres 不知道在哪里可以找到服务器配置文件

    我已经安装了 PostgreSQL 但是当我运行命令时postgres在Windows CMD中 它给出以下错误 postgres does not know where to find the server configuration f
  • qpython android IOError: [Erno 2] 没有这样的文件或目录

    我试图从 qpython 中的简单 python 脚本调用图像 但收到错误消息 qpython android IOError Erno 2 No such file or directory 我想知道我是否使用了正确的目录约定 这是代码
  • C# 泛型用户控件

    我想定义以下控件 public partial class ObjectSelectorControl
  • jQuery AJAX 类型:'GET',传值问题

    我有一个类型为 GET 的 jQuery AJAX 调用 如下所示 ajax type GET url createUser data userId 12345 userName test success function data ale
  • 聚集索引和非聚集索引实际上意味着什么?

    我对 DB 的接触有限 并且仅作为应用程序员使用过 DB 我想了解Clustered and Non clustered indexes 我用谷歌搜索 发现的是 聚集索引是一种特殊类型的索引 它重新排序的方式 表中的记录是物理上的 存储 因
  • 为 ARM 交叉编译 ocaml 应用程序

    我正在交叉编译一个触摸屏驱动程序 它附带一个 ocaml 校准应用程序 我正在尝试编译 ARM 的驱动程序和应用程序 特别是运行 Angstr m 的 Beagleboard 事情是这样的 raziel Bebop zytouch driv
  • 将 jQuery 代码添加到 ASP.NET Boilerplate

    我有一个使用 ASP NET Boilerplate 的项目 我想通过使用 jQuery 添加更多功能 我尝试在页面末尾 例如Home cshtml 写一段简单的代码 如下 看起来完全没有效果 然后我尝试将此代码放入 Home js 文件中
  • SQL 获取 Netezza DB 中的唯一行

    我有一个表 其中的行如下 id group name code 1 999 2 16 3 789 4 999 5 231 6 999 7 349 8 16 9 819 10 999 11 654 但我想要这样的输出行 id group na
  • 如何根据键从对象文字返回值?

    我有一个数组如下 如何检索特定键的值并将该值放入变量中 var obj one 1 two 3 three 5 four 1 five 6 例如 如果我想获取 三 的值 我该如何在 javascript 或 jQuery 中实现呢 您可以通
  • 在 ubuntu 18.04.4LTS 上重新安装 gitlab 后,gitlab-reconfigure 在 redis 上被阻止

    这是我第三次在服务器上安装 gitlab 之前从未遇到过问题 在处理 12 9 0 上的问题后 我决定重新安装 gitlab ce 12 10 0 在安装新版本之前 我已确保删除所有 gitlab 文件并重新启动服务器 步骤1 卸载gitl
  • numpy 中数据类型的奇怪隐式转换

    我创建了一个简单的 numpy 数据类型 uint 如下所示 import numpy as np a np array 1 2 3 dtype np uint 当我计算时 a 0 1 我期望结果为 2 但它给出了 2 0 为什么 np u
  • 如何从通用方法访问类的属性 - C#

    我有一个具有以下属性的三类 Class A public int CustID get set public string Name get set Class B public int CustID get set public stri
  • 强制分配返回的对象[重复]

    这个问题在这里已经有答案了 在 C 中 有没有办法强制对函数的返回值进行赋值 即如果我有一个成员函数 foo class myClass public T1 foo T2 x T1 y something return y 我可以在 mai
  • Android POSIX 兼容吗?

    Android POSIX 兼容吗 我知道它使用 Linux 内核 但我不确定这是否意味着它兼容 POSIX 因为 POSIX 标准更多地处理用户层函数 那么 兼容吗 例如 如果我在 C 程序中仅使用 ANSI 和 POSIX 函数 它是否
  • 如何在 Objective-C 中取消安排 NSTimer

    我在应用程序中使用嵌套 NSTimer 我这里有两个问题 如何在此函数中重新启动计时器 void updateLeftTime NSTimer theTimer 如何杀死之前的计时器 因为 void updateLevel NSTimer
  • faunadb中如何进行多条件查询?

    我尝试提高对 FaunaDB 的理解 我有一个包含以下记录的集合 ref Ref Collection regions 261442015390073344 ts 1587576285055000 data name italy attri
  • Python:从文件夹中读取多个json文件

    我想知道如何阅读几本json来自单个文件夹的文件 不指定文件名 只是它们是 json 文件 此外 还可以将它们变成pandas数据框 你能给我一个基本的例子吗 一种选择是列出目录中的所有文件操作系统列表目录 https docs pytho