简体   繁体   中英

how to write data in the sequential format in the dataframe

import json
import pandas as pd
import numpy as np


class Decoder(json.JSONDecoder):
    def decode(self, s):
        result = super(Decoder, self).decode(s)
        return self._decode(result)

    def _decode(self, o):
        if isinstance(o, str):
            try:
                return int(o)
            except ValueError:
                try:
                    return float(o)
                except ValueError:
                    return o
        elif isinstance(o, dict):
            return {k: self._decode(v) for k, v in o.items()}
        elif isinstance(o, list):
            return [self._decode(v) for v in o]
        else:
            return o


with open('ouput_data.json') as f:
    data = json.load(f, cls=Decoder)

list = []
list = (data['data'])
df = pd.DataFrame(list, columns=['id', 'value'])
new_df = df.set_index('id')
new_df1 = new_df.reindex(np.arange(1, 14)).fillna(' ')
print(new_df1)

which giving the output like,

 id              value
  1            whats up
  2                what
  3                    
  4                    
  5                  HI
  6                    
  7                    
  8                    
  9                    
 10                    
 11                    
 12                    
 13   

But i want output like sequentially,how can i edit the code to achieve this output

id      1       2     3   4   5   6   7   8   9   10   11   12   13
value  whatsup  what          Hi

Let me know guys where i have to change in existing the code only !!!! please!!!!!

Thanks in advance

Your three lines:

df = pd.DataFrame(list,columns=['id','value'])
new_df = df.set_index('id')
new_df1=new_df.reindex(np.arange(1, 14)).fillna(' ')

can be rewritten as:

df = (pd.DataFrame(list, columns = ['id','value'])
        .set_index('id')
        .reindex(np.arange(1, 14)).fillna(' ')
        .T
     )

and df is what you are after.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM