【问题标题】:Combinging Multiple Json Objects as one DataFrame in Python Pandas在 Python Pandas 中将多个 Json 对象组合为一个 DataFrame
【发布时间】:2014-02-08 17:30:24
【问题描述】:

我不确定我在这里遗漏了什么,但我有 2 个包含 json 文件的 zip 文件,我只是试图合并从文件中提取的数据并合并为一个数据框,但我的循环不断给我单独的记录。这是我在构建 DF 之前所拥有的。我尝试了 pd.concat 但我认为我的问题更多与我首先阅读文件的方式有关。

data = []
for FileZips in glob.glob('*.zip'):
    with zipfile.ZipFile(FileZips, 'r') as myzip:
        for logfile in myzip.namelist():
            with myzip.open(logfile) as f:
                contents = f.readlines()[-2]
                jfile = json.loads(contents)
                print len(jfile)

返回:

40935 
40935

【问题讨论】:

    标签: python json pandas


    【解决方案1】:

    您可以使用read_json(假设它是有效 json)。

    为了便于阅读,我还将其分解为更多功能:

    def zip_to_df(zip_file):
        with zipfile.ZipFile(zip_file, 'r') as myzip:
            return pd.concat((log_as_df(loglife, myzip)
                                 for logfile in myzip.namelist()),
                             ignore_index=True)
    
    def log_as_df(logfile, myzip):
        with myzip.open(logfile, 'r') as f:
            contents = f.readlines()[-2]
            return pd.read_json(contents)
    
    df = pd.concat(map(zip_to_df, glob.glob('*.zip')), ignore_index=True)
    

    注意:这会做更多的连接,但我认为它的可读性是值得的,你可以只做一个连接......

    【讨论】:

      【解决方案2】:

      我能够通过对缩进进行小的调整来获得所需的内容!

      dfs = []
      for FileZips in glob.glob('*.zip'):
          with zipfile.ZipFile(FileZips, 'r') as myzip:
              for logfile in myzip.namelist():
                  with myzip.open(logfile, 'r') as f:
                      contents = f.readlines()[-2]
                      jfile = json.loads(contents)
                      dfs.append(pd.DataFrame(jfile))
                      df = pd.concat(dfs, ignore_index=True)
      print len(df) 
      

      【讨论】:

      • 我认为您可以将 concat 从所有缩进中取出。我的感觉是,为了便于阅读,应该将其分解为单独的函数。
      猜你喜欢
      • 2018-04-08
      • 1970-01-01
      • 2016-04-30
      • 2014-01-08
      • 2017-09-13
      • 2016-02-25
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      相关资源
      最近更新 更多