Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将所有列设置为索引,或将数据帧转换为多索引系列_Python_Python 3.x_Pandas_Dataframe_Series - Fatal编程技术网

Python 将所有列设置为索引,或将数据帧转换为多索引系列

Python 将所有列设置为索引,或将数据帧转换为多索引系列,python,python-3.x,pandas,dataframe,series,Python,Python 3.x,Pandas,Dataframe,Series,我有以下数据帧: from to x ratea 1 2 0.4 10 1 4 0.6 80 1 5 0.2 10 2 3 0.2 10 2 4 0.4 10 2 6 0.3 10 3 5 0.2 10 4 6 0.3 10 我的目标是实现以下目标: from to 1 2 x 0.

我有以下数据帧:

from    to  x     ratea
1       2   0.4   10
1       4   0.6   80
1       5   0.2   10
2       3   0.2   10
2       4   0.4   10
2       6   0.3   10
3       5   0.2   10
4       6   0.3   10
我的目标是实现以下目标:

from    to      
1   2   x       0.4
1   2   ratea   10
1   4   x       0.6
1   4   ratea   80
1   5   x       0.2
1   5   ratea   10
2   3   x       0.2
2   3   ratea   10
2   4   x       0.4
2   4   ratea   10
2   6   x       0.3
2   6   ratea   10
3   5   x       0.2
3   5   ratea   10
4   6   x       0.3
4   6   ratea   10
我将如何进行此转换

PS
unstack()
也没有帮助(或者我可能没有使用它)。

用于设置新索引名:

s = df.set_index(['from','to']).stack().rename_axis(['from','to','val'])
print (s)

from  to  val  
1     2   x         0.4
          ratea    10.0
      4   x         0.6
          ratea    80.0
      5   x         0.2
          ratea    10.0
2     3   x         0.2
          ratea    10.0
      4   x         0.4
          ratea    10.0
      6   x         0.3
          ratea    10.0
3     5   x         0.2
          ratea    10.0
4     6   x         0.3
          ratea    10.0
dtype: float64

非常感谢你。你不知道在这上面浪费了多少时间。你是个救命恩人:)你回答得太快了,我无法接受答案:)我显然要等10分钟:)有没有办法让我给那列命名,这样我就可以把所有这些列都列为索引,也就是说,我如何将其转换为多索引系列?