python - 如何使用 Pandas 对数据帧索引进行重新排序/排序?

标签 python sorting pandas

我得到了一些数据:

# 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

我使用 sortsort_indexsort_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/

相关文章:

python - 为什么 QPropertyAnimation 动画不起作用?

python - 扩展类(Monkey Patching)如何在 Python 中工作?

c - 尝试对结构进行排序但出现错误或崩溃

python - 将标准格式日期字符串转换为日期时间对象

python - 将带有值的按钮重定向到其他 django 模板/ View

python - 如何解决 anaconda 中的 CondaHTTPError 问题?

PHP - 对多维数组进行排序时出现问题?

python - 在 Pandas 中将 DatetimeIndex 向前滚动到下一个营业月的开始

python - 如何计算以多列作为参数的 pandas 列?

python - 如何摆脱行号,pd.read_excel?