56_Pandas读取 JSON 字符串/文件 (read_json)

[复制链接]
查看522 | 回复0 | 2023-8-23 11:47:44 | 显示全部楼层 |阅读模式
56_Pandas读取 JSON 字符串/文件 (read_json)

利用pandas.read_json()函数,可以将JSON格式字符串(str类型)和文件读取为pandas.DataFrame。它还支持 JSON 行 (.jsonl)。
读取成pandas.DataFrame后,可以做各种数据分析,也可以用to_csv()方法生存成csv文件,如许就可以很方便的通过pandas将JSON文件转为CSV文件。


  • 34_Pandas对CSV文件内容的导出和添加(to_csv)
在此,对以下内容举行阐明。


  • pandas.read_json() 的根本用法

    • 读取 JSON 格式字符串
    • 读取JSON格式文件

      • 读取压缩文件:参数compression


  • 指定格式:参数orient
  • 读取 JSON 行 (.jsonl)
  • 读取 JSON 字符串/文件的一部分
pandas.read_json() 的根本用法

用作示例的字符串和文件是在以下文章中创建的。


  • 55_Pandas.DataFrame 转换为 JSON 字符串/文件并生存 (to_json)
读取 JSON 格式字符串

如果将 JSON 格式的字符串转达给 pandas.read_json() 函数的第一个参数,该字符串将被转换为 pandas.DataFrame。
  1. import pandas as pd
  2. import json
  3. s = '{"col1":{"row1":1,"row2":2,"row3":3},"col2":{"row1":"a","row2":"x","row3":"\u554a"}}'
  4. df_s = pd.read_json(s)
  5. print(df_s)
  6. #       col1 col2
  7. # row1     1    a
  8. # row2     2    x
  9. # row3     3    啊
复制代码
将原始字符串中的 Unicode 转义序列 \uXXXX 转换为相应的字符。 留意JSON字符串中的引号必须是双引号"。单引号’会导致错误(ValueError)。
  1. s_single_quote = "{'col1':{'row1':1,'row2':2,'row3':3},'col2':{'row1':'a','row2':'x','row3':'\u554a'}}"
  2. # df_s_single_quote = pd.read_json(s_single_quote)
  3. # ValueError: Expected object or value
复制代码
对于利用单引号 ’ 的字符串,利用字符串方法 replace() 将单引号 ’ 更换为双引号 "。
  1. print(pd.read_json(s_single_quote.replace("'", '"')))
  2. #       col1 col2
  3. # row1     1    a
  4. # row2     2    x
  5. # row3     3    啊
复制代码
读取JSON格式文件

如果将 JSON 格式文件路径转达给 pandas.read_json() 函数的第一个参数,该文件将被读取为 pandas.DataFrame。
  1. df_f = pd.read_json('data/sample_from_pandas_columns.json')
  2. print(df_f)
  3. #       col1 col2
  4. # row1     1    a
  5. # row2     2    x
  6. # row3     3    啊
复制代码
读取压缩文件:参数compression

pandas 0.21.0版本参加了参数compression,指定’gzip’, ‘bz2’, ‘zip’, 'xz’可以直接读取压缩文件。
如果扩展名是.gz、.bz2、.zip、.xz,设置compression='infer’会主动选择对应的压缩方式。
  1. df_gzip = pd.read_json('data/sample_from_pandas_columns.gz', compression='infer')
  2. print(df_gzip)
  3. #       col1 col2
  4. # row1     1    a
  5. # row2     2    x
  6. # row3     3    啊
复制代码
请留意,这仅适用于压缩的单个文件,无法读取包罗多个文件的 zip。
指定格式:参数orient

pandas.DataFrame的行标签index、column标签column、value值怎样赋值JSON的内容有以下几种格式。


  • ‘split’

    • {index -> [index], columns -> [columns], data -> [values]}

  • ‘records’

    • [{column -> value}, … , {column -> value}]

  • ‘index’

    • {index -> {column -> value}}

  • ‘columns’(default)

    • {column -> {index -> value}}

  • ‘values’

    • [values]

有关实际示例,请参阅下面的文章。


  • 55_Pandas.DataFrame 转换为 JSON 字符串/文件并生存 (to_json)
留意,如果要读取的字符串或文件的格式与orient参数中指定的格式不同,会导致行列互换或堕落。
  1. df_s_index = pd.read_json(s, orient='index')
  2. print(df_s_index)
  3. #      row1 row2 row3
  4. # col1    1    2    3
  5. # col2    a    x    啊
  6. # df_s_split = pd.read_json(s, orient='split')
  7. # ValueError: JSON data had unexpected key(s): col2, col1
复制代码
读取 JSON 行 (.jsonl)

JSON 行 (.jsonl) 是用换行符分隔的 JSON。
如果参数 orient=‘records’ 和参数 lines=True,您可以利用 pandas.read_json() 读取 JSON 行 (.jsonl)。
  1. s_jsonl = '''{"col1":1,"col2":"a"}
  2. {"col1":2,"col2":"x"}
  3. {"col1":3,"col2":"\u554a"}'''
  4. print(s_jsonl)
  5. # {"col1":1,"col2":"a"}
  6. # {"col1":2,"col2":"x"}
  7. # {"col1":3,"col2":"啊"}
  8. df_s_jsonl = pd.read_json(s_jsonl, orient='records', lines=True)
  9. print(df_s_jsonl)
  10. #    col1 col2
  11. # 0     1    a
  12. # 1     2    x
  13. # 2     3    啊
复制代码
要读取 JSONL 文件,只需在第一个参数中指定文件路径,如上例所示。
读取 JSON 字符串/文件的一部分

究竟上,可以通过Web API等获取的JSON除了作为pandas.DataFrame读取的数据之外另有其他信息,因此在很多情况下不能直策应用pandas.read_json()。
在这种情况下,可以按以鄙俚程阅读。大概有更好的方法。
1.利用标准库json模块的json.loads()和json.load()将JSON字符串和文件作为
2.字典读取 从字典中提取你想读的部分
3.利用 json.dumps() 将提取的部分转换为字符串
4.将字符串转达给 pandas.read_json()
以下面的嵌套 JSON 字符串为例。
  1. s_nested = '{"OTHER": "x", "DATA": {"col1":{"row1":1,"row2":2},"col2":{"row1":"a","row2":"x"}}}'
复制代码
如果按原样转达给 pandas.read_json() ,它将如下所示。
  1. print(pd.read_json(s_nested))
  2. #                             DATA OTHER
  3. # col1      {'row1': 1, 'row2': 2}     x
  4. # col2  {'row1': 'a', 'row2': 'x'}     x
复制代码
起首,利用 json.loads() 将其转换为字典。 json.load() 加载文件。
  1. d = json.loads(s_nested)
  2. print(d)
  3. # {'OTHER': 'x', 'DATA': {'col1': {'row1': 1, 'row2': 2}, 'col2': {'row1': 'a', 'row2': 'x'}}}
  4. print(type(d))
  5. # <class 'dict'>
复制代码
从字典中提取要读取的部分作为 pandas.DataFrame。如果嵌套很深,则重复 [key name] [key name]。
  1. d_target = d['DATA']
  2. print(d_target)
  3. # {'col1': {'row1': 1, 'row2': 2}, 'col2': {'row1': 'a', 'row2': 'x'}}
  4. print(type(d_target))
  5. # <class 'dict'>
复制代码
利用 json.dumps() 转换为字符串。
  1. s_target = json.dumps(d_target)
  2. print(s_target)
  3. # {"col1": {"row1": 1, "row2": 2}, "col2": {"row1": "a", "row2": "x"}}
  4. print(type(s_target))
  5. # <class 'str'>
复制代码
转达给 pandas.read_json()。根据格式指定参数方向。示例默认值(orient=‘columns’)。
  1. df_target = pd.read_json(s_target)
  2. print(df_target)
  3. #       col1 col2
  4. # row1     1    a
  5. # row2     2    x
复制代码
一起写也OK了。
  1. df_target2 = pd.read_json(json.dumps(json.loads(s_nested)['DATA']))
  2. print(df_target2)
  3. #       col1 col2
  4. # row1     1    a
  5. # row2     2    x
复制代码
如果你要阅读的部分是orient=‘records’(字典列表)格式,你可以利用pandas.io.json.json_normalize()将字典列表直接转换为pandas.DataFrame。

来源:https://blog.csdn.net/qq_18351157/article/details/128555163
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则