Export pandas dataframe to json and back to a dataframe with columns in the same order
You can use parameter orient='split'
in to_json/read_json
which also save in json column names in list in original ordering:
df = pd.DataFrame({ 'C':list('abcdef'), 'B':[4,5,4,5,5,4], 'A':[7,8,9,4,2,3],})print (df.to_json(orient='split')){"columns":["C","B","A"], "index":[0,1,2,3,4,5], "data":[["a",4,7],["b",5,8], ["c",4,9],["d",5,4],["e",5,2],["f",4,3]]}df.to_json('file.json', orient='split')df = pd.read_json('file.json', orient='split')print (df) C B A0 a 4 71 b 5 82 c 4 93 d 5 44 e 5 25 f 4 3
Another alternative:
df.to_pickle('file')df = pd.read_pickle('file')
And next alternative is add to json columns names in list:
import jsonj = {'columns': df.columns.tolist(), 'data' : df.to_dict(orient='records')}print (j){'columns': ['C', 'B', 'A'], 'data': [{'C': 'a', 'B': 4, 'A': 7}, {'C': 'b', 'B': 5, 'A': 8}, {'C': 'c', 'B': 4, 'A': 9}, {'C': 'd', 'B': 5, 'A': 4}, {'C': 'e', 'B': 5, 'A': 2}, {'C': 'f', 'B': 4, 'A': 3}]}file = 'file.json'with open(file, 'w') as f_obj: json.dump(j, f_obj)with open(file) as f_obj: json_data = json.load(f_obj)df = pd.DataFrame(json_data['data'], columns=json_data['columns'])print(df) C B A0 a 4 71 b 5 82 c 4 93 d 5 44 e 5 25 f 4 3