【问题标题】:Keep column and row order when storing pandas dataframe in json在 json 中存储 pandas 数据帧时保持列和行顺序
【发布时间】:2017-09-20 04:57:19
【问题描述】:

当使用 to_json 将数据存储在 json 对象中并使用 read_json 读回时,行和列按字母顺序返回。有没有办法在检索时保持结果有序或重新排序?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    假设您有一个可以阅读的 pandas 数据框

    import pandas as pd
    df = pd.read_json ('/abc.json')
    df.head()
    

    提供以下信息

    现在有两种方法可以使用 pandas to_json 保存到 json result.sample(200).to_json('abc_sample.json',orient='split') 这将给出这样一列的顺序

    但是,要保留 csv 中的顺序,请使用这个

    result.sample(200).to_json('abc_sample_2nd.json',orient='records')
    

    这将给出结果

    【讨论】:

      【解决方案2】:

      如果你想用“orient='records'”创建一个格式并保持列的顺序,试着做一个这样的函数。我不认为这是一个明智的做法,也不推荐,因为它不能保证它的顺序。

      def df_to_json(df):
          res_arr = []
          ldf = df.copy()
          ldf=ldf.fillna('')
          lcolumns = [ldf.index.name] + list(ldf.columns)
          for key, value in ldf.iterrows():
              lvalues = [key] + list(value)
              res_arr.append(dict(zip(lcolumns, lvalues)))
          return json.dumps(res_arr)
      

      另外,对于没有排序列的阅读,请参考这个[链接](Python json.loads changes the order of the object

      祝你好运

      【讨论】:

        【解决方案3】:

        您可以使用orient='split',它将索引和列信息存储在列表中,从而保持顺序:

        In [34]: df
        Out[34]: 
           A  C  B
        5  0  1  2
        4  3  4  5
        3  6  7  8
        
        In [35]: df.to_json(orient='split')
        Out[35]: '{"columns":["A","C","B"],"index":[5,4,3],"data":[[0,1,2],[3,4,5],[6,7,8]]}'
        
        In [36]: pd.read_json(df.to_json(orient='split'), orient='split')
        Out[36]: 
           A  C  B
        5  0  1  2
        4  3  4  5
        3  6  7  8
        

        记得在阅读时也使用orient='split',否则你会得到

        In [37]: pd.read_json(df.to_json(orient='split'))
        Out[37]: 
          columns       data  index
        0       A  [0, 1, 2]      5
        1       C  [3, 4, 5]      4
        2       B  [6, 7, 8]      3
        

        【讨论】:

        • 我有一堆日期,它们被转换为纪元时间戳,而原始格式是 YYYY-MM-DD。如何保留订单和日期格式?
        • @Naveen,你需要在read_json()之后手动设置dtypes,像这样df['date_operation'] = df['date_operation'].astype('datetime64[ms]') . This convert default milliseconds produced by df.to_json()`
        猜你喜欢
        • 1970-01-01
        • 2019-08-24
        • 1970-01-01
        • 2016-02-05
        • 2018-09-10
        • 1970-01-01
        • 2017-08-08
        • 2020-04-25
        • 1970-01-01
        相关资源
        最近更新 更多