在 pandas 中加载 json 文件
本教程介绍了如何使用 pandas.read_json()
方法将一个 json 文件加载到 pandas dataframe 中。
将 json 文件加载到 pandas dataframe 中
我们可以使用 pandas.read_json()
函数将 json 文件的路径作为参数传递给 pandas.read_json()
函数,将 json 文件加载到 pandas dataframe 中。
{
"name": {"1": "anil", "2": "biraj", "3": "apil", "4": "kapil"},
"age": {"1": 23, "2": 25, "3": 28, "4": 30},
}
示例 data.json
文件的内容如上所示。我们将从上述 json 文件中创建一个 dataframe。
import pandas as pd
df = pd.read_json("data.json")
print("dataframe generated using json file:")
print(df)
输出:
dataframe generated using json file:
name age
1 anil 23
2 biraj 25
3 apil 28
4 kapil 30
它显示的是由 data.json
文件中的数据生成的 dataframe。我们必须确保在当前工作目录下有 data.json
文件才能生成 dataframe,否则我们需要提供 json 文件的完整路径作为 pandas.read_json()
方法的参数。
由 json 文件形成的 dataframe 取决于 json 文件的方向。我们一般有三种不同的 json 文件的面向。
- 面向索引
- 面向值
- 面向列
将面向索引的 json 文件加载到 pandas dataframe 中
{
"0": {"name": "anil", "age": 23},
"1": {"name": "biraj", "age": 25},
"2": {"name": "apil", "age": 26},
}
这是一个面向索引的 json 文件的例子,其中顶层键代表数据的索引。
import pandas as pd
df = pd.read_json("data.json")
print("dataframe generated from index oriented json file:")
print(df)
输出:
dataframe generated from index oriented json file:
0 1 2
name anil biraj apil
age 23 25 26
它将从 data.json
文件中创建一个 dataframe,顶层键在 dataframe 中表示为列。
将面向值的 json 文件加载到 pandas dataframe 中
[["anil", 23], ["biraj", 25], ["apil", 26]]
这是一个面向值的 json 文件的例子,数组中的每个元素代表每一行的值。
import pandas as pd
df = pd.read_json("data.json")
print("dataframe generated from value oriented json file:")
print(df)
输出:
dataframe generated from value oriented json file:
0 1
0 anil 23
1 biraj 25
2 apil 26
它将从 data.json
文件中创建一个 dataframe,json 文件中数组的每个元素将在 dataframe 中表示为一行。
将面向列的 json 文件加载到 pandas dataframe 中
{"name": {"1": "anil", "2": "biraj", "3": "apil"}, "age": {"1": 23, "2": 25, "3": 28}}
它是一个面向列的 json 文件顶层索引的例子,代表数据的列名。
import pandas as pd
df = pd.read_json("data.json")
print("dataframe generated from column oriented json file:")
print(df)
输出:
dataframe generated from column oriented json file:
name age
1 anil 23
2 biraj 25
3 apil 28
它将从 data.json
文件中创建一个 dataframe,json 文件的顶层索引将作为 dataframe 中的列名。
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
pandas dataframe dataframe.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:python
-
dataframe.shift() 函数是将 dataframe 的索引按指定的周期数进行移位。
python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:python
-
python pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:python
-
pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 dataframe 中。
pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:python
-
本教程介绍了如何在 pandas 中使用 dataframe.merge()方法合并两个 dataframes。
pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:python
-
本教程介绍了如何使用 python 中的 loc 和 iloc 从 pandas dataframe 中过滤数据。
在 python 中将 pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:python
-
了解如何在 python 中将 pandas 系列日期时间转换为字符串