Python 如何防止pandas在JSON转换期间更改多索引数据帧结构?
我最初有以下数据帧:Python 如何防止pandas在JSON转换期间更改多索引数据帧结构?,python,json,pandas,dataframe,Python,Json,Pandas,Dataframe,我最初有以下数据帧: cat cat 1 1 1 1 1 dog 0 0 0 0 0 fox 0 0 0 0 0 jumps 1 1 1 1 1 mouse 1 1 1 1 1 over 1 1 1 1 1 the 1 1 1 1 1 dog cat 0 0 0 0 0 dog 1 1 1 1
cat cat 1 1 1 1 1
dog 0 0 0 0 0
fox 0 0 0 0 0
jumps 1 1 1 1 1
mouse 1 1 1 1 1
over 1 1 1 1 1
the 1 1 1 1 1
dog cat 0 0 0 0 0
dog 1 1 1 1 1
fox 1 1 1 1 1
jumps 1 1 1 1 1
mouse 0 0 0 0 0
over 1 1 1 1 1
the 1 1 1 1 1
fox cat 0 0 0 0 0
dog 1 1 1 1 1
fox 1 1 1 1 1
jumps 1 1 1 1 1
mouse 0 0 0 0 0
over 1 1 1 1 1
the 1 1 1 1 1
jumps cat 1 1 1 1 1
dog 1 1 1 1 1
fox 1 1 1 1 1
jumps 1 1 1 1 1
mouse 1 1 1 1 1
over 1 0 1 1 1
the 1 0 1 1 1
mouse cat 1 1 1 1 1
dog 0 0 0 0 0
fox 0 0 0 0 0
jumps 1 1 1 1 1
mouse 1 1 1 1 1
over 1 1 1 1 1
the 1 1 1 1 1
over cat 1 1 1 1 1
dog 1 1 1 1 1
fox 1 1 1 1 1
jumps 1 1 0 1 0
mouse 1 1 1 1 1
over 1 1 1 1 1
the 1 0 1 1 1
the cat 1 1 1 1 1
dog 1 1 1 1 1
fox 1 1 1 1 1
jumps 1 1 0 1 1
mouse 1 1 1 1 1
over 1 1 0 1 0
the 1 1 1 1 1
然后我使用以下方法将其转换为JSON格式:
JSON = df.reset_index().to_json()
new_df = pd.read_json(JSON)
重置索引,因为无法直接将多索引df转换为JSON
然后,我使用以下方法将其恢复为数据帧格式:
JSON = df.reset_index().to_json()
new_df = pd.read_json(JSON)
但现在当我打印它时,它显示以下数据帧:
0 1 1 1 1 1 cat cat
1 0 0 0 0 0 cat dog
10 1 1 1 1 1 dog jumps
11 0 0 0 0 0 dog mouse
12 1 1 1 1 1 dog over
13 1 1 1 1 1 dog the
14 0 0 0 0 0 fox cat
15 1 1 1 1 1 fox dog
16 1 1 1 1 1 fox fox
17 1 1 1 1 1 fox jumps
18 0 0 0 0 0 fox mouse
19 1 1 1 1 1 fox over
2 0 0 0 0 0 cat fox
20 1 1 1 1 1 fox the
21 1 1 1 1 1 jumps cat
22 1 1 1 1 1 jumps dog
23 1 1 1 1 1 jumps fox
24 1 1 1 1 1 jumps jumps
25 1 1 1 1 1 jumps mouse
26 1 0 1 1 1 jumps over
27 1 0 1 1 1 jumps the
28 1 1 1 1 1 mouse cat
29 0 0 0 0 0 mouse dog
3 1 1 1 1 1 cat jumps
30 0 0 0 0 0 mouse fox
31 1 1 1 1 1 mouse jumps
32 1 1 1 1 1 mouse mouse
33 1 1 1 1 1 mouse over
34 1 1 1 1 1 mouse the
35 1 1 1 1 1 over cat
36 1 1 1 1 1 over dog
37 1 1 1 1 1 over fox
38 1 1 0 1 0 over jumps
39 1 1 1 1 1 over mouse
4 1 1 1 1 1 cat mouse
40 1 1 1 1 1 over over
41 1 0 1 1 1 over the
42 1 1 1 1 1 the cat
43 1 1 1 1 1 the dog
44 1 1 1 1 1 the fox
45 1 1 0 1 1 the jumps
46 1 1 1 1 1 the mouse
47 1 1 0 1 0 the over
48 1 1 1 1 1 the the
5 1 1 1 1 1 cat over
6 1 1 1 1 1 cat the
7 0 0 0 0 0 dog cat
8 1 1 1 1 1 dog dog
9 1 1 1 1 1 dog fox
正如你所看到的,结构已经完全改变了。在与JSON的转换过程中,有什么方法可以保持数据帧的结构完全相同吗?这里的索引只是添加了sort\u索引
这不起作用,但df仍然在结构上保持不变damaged@Elisha512在您将之前的_索引重置为_json后,df仍然会在那里受到结构损坏,以便在不损坏结构的情况下将其保存为json?@Elisha512您知道您可以将其转换回右侧吗?@Elisha512 pd.read_json.sort_index.set_index['level_0','level_1']