我写了两个小程序:
- 第一个将数据从 .txt 文件导入到 pandas 数据框中,处理数据并将最终数据导出到 json 文件。
- 第二个代码将该 json 文件中的数据导入回数据框中。
不幸的是,当从 json 文件导入数据时,列的顺序发生了变化。我在网上看过几个示例,其中 OrderedDict
用于在新表中创建固定结构,但如何将 OrderedDict
应用于现有表?
我已经尝试了几个版本,包括以下几个,但都没有用:
df = OrderedDict(pd.DataFrame.from_dict(json_data, orient='columns'))
和
data = OrderedDict(pd.read_csv('wtx2015.txt', sep=",", header=None))
代码:.txt>pandas数据框>json
import pandas as pd
import json
from pandas import DataFrame
from collections import OrderedDict
pd.set_option("max_columns", 50)
"""Defining functions"""
data = pd.read_csv('wtx2015.txt', sep=",", header=None)
data.columns = ["category1", "category2", "category3", "category4"]
"""Manipulating data"""
print(data.head(n=3))
df = DataFrame(data, columns= ["category1", "category2", "category3", "category4", "category5"])
final = df.to_json(orient='records')
with open('pandas_test.json', 'w') as f_obj:
f_obj.write(final)
代码:json > pandas数据框
import pandas as pd
import json
file = 'pandas_test.json'
with open(file) as f_obj:
json_data = json.load(f_obj)
df = pd.DataFrame.from_dict(json_data, orient='columns')
print(df)
最佳答案
您可以在 to_json/read_json
中使用参数 orient='split'
,它也以原始顺序保存在列表中的 json 列名中:
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 A
0 a 4 7
1 b 5 8
2 c 4 9
3 d 5 4
4 e 5 2
5 f 4 3
另一种选择:
df.to_pickle('file')
df = pd.read_pickle('file')
下一个替代方法是添加到列表中的 json 列名称:
import json
j = {'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 A
0 a 4 7
1 b 5 8
2 c 4 9
3 d 5 4
4 e 5 2
5 f 4 3
关于python - 将 pandas 数据框导出到 json 并返回到具有相同顺序列的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53909346/