如何在数据帧中以顺序格式写入数据


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)

给出这样的输出,

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

但是我想要像顺序一样的输出,如何编辑代码来实现此输出

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

请让我知道我必须在现有代码中更改!!!!!!!

提前致谢

你的三行:

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

可以改写为:

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

df就是你所追求的。

最新更新