【问题标题】:Convert Pandas DataFrame to JSON format将 Pandas DataFrame 转换为 JSON 格式
【发布时间】:2017-01-08 11:44:18
【问题描述】:

我有一个 Pandas DataFrame 有两列——一列是文件名,另一列是生成时间:

 File       Hour
  F1         1
  F1         2
  F2         1
  F3         1

我正在尝试将其转换为具有以下格式的 JSON 文件:

{"File":"F1","Hour":"1"} 
{"File":"F1","Hour":"2"}
{"File":"F2","Hour":"1"}
{"File":"F3","Hour":"1"}

当我使用命令DataFrame.to_json(orient = "records") 时,我得到以下格式的记录:

[{"File":"F1","Hour":"1"},
 {"File":"F1","Hour":"2"},
 {"File":"F2","Hour":"1"},
 {"File":"F3","Hour":"1"}]

我只是想知道是否可以选择以所需格式获取 JSON 文件。任何帮助将不胜感激。

【问题讨论】:

  • 你想要的不是正确的json。你从dataframe.to_json(orient = “records”) 得到的是正确的json

标签: json pandas dataframe


【解决方案1】:

DF.to_json 之后得到的输出是string。因此,您可以根据自己的要求简单地对其进行切片并从中删除逗号。

out = df.to_json(orient='records')[1:-1].replace('},{', '} {')

要将输出写入文本文件,您可以这样做:

with open('file_name.txt', 'w') as f:
    f.write(out)

【讨论】:

  • 这将删除两个键值对之间的逗号:{"ServerGroup":"Map""Hour":0}。我需要它是 {"ServerGroup":"Map","Hour":0}。
  • 是的,那是我的错误。请尝试修改后的。
  • 谢谢,效果很好。最初,我使用“df1.to_json(orient='records',path_or_buf='/content/tmp/GoogleCount.json')[1:-1] 将数据帧转换为 json 文件并将其存储在本地文件中。代替('},{','} {')”。但是现在在替换语句之后,我收到错误“'NoneType' object has no attribute 'getitem'”
  • 那是因为它不再是json 格式化对象,而是json-string。尝试将 path_or_buf=None 作为参数传递。
  • 好的,谢谢。但是我需要将它保存在一个文件中,只是想知道有没有办法实现它
【解决方案2】:

在较新版本的 pandas(我相信是 0.20.0+)中,可以直接这样做:

df.to_json('temp.json', orient='records', lines=True)

也可以直接压缩:

df.to_json('temp.json.gz', orient='records', lines=True, compression='gzip')

【讨论】:

  • 最好的解决方案恕我直言!
  • JEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEZ 我已经坚持了这么久,它太愚蠢了,你救了我非常感谢(由于某种原因我不能使用临时 CSV),无论如何,谢谢!
【解决方案3】:

我认为 OP 正在寻找的是:

with open('temp.json', 'w') as f:
    f.write(df.to_json(orient='records', lines=True))

这应该可以解决问题。

【讨论】:

  • 应该是最佳答案。简洁明了。
【解决方案4】:

使用此公式将 pandas DataFrame 转换为字典列表:

import json
json_list = json.loads(json.dumps(list(DataFrame.T.to_dict().values())))

【讨论】:

    【解决方案5】:

    试试这个:

    json.dumps(json.loads(df.to_json(orient="records")))

    【讨论】:

      【解决方案6】:

      要在真正的 json(不是字符串)中转换数据帧,我使用:

          from io import StringIO
          import json
          import DataFrame
      
          buff=StringIO()
          #df is your DataFrame
          df.to_json(path_or_buf=buff,orient='records')
          dfJson=json.loads(buff)
      

      【讨论】:

        【解决方案7】:

        将数据框转换为字典列表

        list_dict = []
        
        for index, row in list(df.iterrows()):
            list_dict.append(dict(row))
        

        保存文件

        with open("output.json", mode) as f:
            f.write("\n".join(str(item) for item in list_dict))
        

        【讨论】:

          【解决方案8】:

          而不是使用dataframe.to_json(orient = “records”) 使用dataframe.to_json(orient = “index”) 我上面的代码将数据框转换为 dict 的 json 格式,例如 {index -> {column -> value}}

          【讨论】:

          • 也许,这取决于您尝试使用的数据的方向。
          【解决方案9】:

          这是一个将 JSON 转换为 DataFrame 并返回的小型实用程序类:希望对您有所帮助。

          # -*- coding: utf-8 -*-
          from pandas.io.json import json_normalize
          
          class DFConverter:
          
              #Converts the input JSON to a DataFrame
              def convertToDF(self,dfJSON):
                  return(json_normalize(dfJSON))
          
              #Converts the input DataFrame to JSON 
              def convertToJSON(self, df):
                  resultJSON = df.to_json(orient='records')
                  return(resultJSON)
          

          【讨论】:

          • 有效,但实际上只是相同可用 oneliner 函数的包装器。我认为大多数情况下,这种形式是没有根据的。
          猜你喜欢
          • 1970-01-01
          • 2021-12-29
          • 2021-02-24
          • 2017-04-13
          • 2021-03-29
          • 1970-01-01
          • 2014-01-05
          • 1970-01-01
          相关资源
          最近更新 更多