我得到了一些数据:
# 3 Experiments 0,1 and 2.
# 2 Setups 'foo' and 'bar'
# 3 Measured parameters 'a', 'b' and 'c'
d = {0: {'foo': {'a': 12.68, 'b': 54.44, 'c': 83.98},
'bar': {'a': 11.73, 'b': 53.34, 'c': 82.93}},
2: {'foo': {'a': 11.12, 'b': 57.99, 'c': 81.05},
'bar': {'a': 10.05, 'b': 56.12, 'c': 80.01}},
1: {'foo': {'a': 13.41, 'b': 54.32, 'c': 82.74},
'bar': {'a': 12.77, 'b': 53.15, 'c': 82.01}}}
我将它们导入到 Pandas 中
ds = (pd.DataFrame.from_dict(d, orient='index')
.stack().apply(pd.Series)
.rename_axis(['experiment', 'setup']))
这样就可以很好地显示:
a b c
experiment setup
0 foo 12.68 54.44 83.98
bar 11.73 53.34 82.93
2 foo 11.12 57.99 81.05
bar 10.05 56.12 80.01
1 foo 13.41 54.32 82.74
bar 12.77 53.15 82.01
您注意到实验的顺序错误,并且设置也未排序。所以我想对索引进行排序以将其显示如下:
a b c
experiment setup
0 bar 11.73 53.34 82.93
foo 12.68 54.44 83.98
1 bar 12.77 53.15 82.01
foo 13.41 54.32 82.74
2 bar 10.05 56.12 80.01
foo 11.12 57.99 81.05
我使用 sort
、sort_index
、sort_values
甚至 sortlevel
尝试了很多东西,但我没有似乎有效。我还尝试使用 reset_index
展平所有内容,并再次尝试使用 sort
,但它不起作用。
如何根据需要对数据帧进行排序或重新排序?
最佳答案
很奇怪的是,sort_index
没有按预期工作,但我设法通过重置索引、排序值并将索引设置回预期的输出:
ds = ds.reset_index()\
.sort_values(by=['experiment','setup'])\
.set_index(['experiment','setup'])
关于python - 如何使用 Pandas 对数据帧索引进行重新排序/排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43155417/