【问题标题】:Set all columns as index, or convert a dataframe to a multiindex series将所有列设置为索引,或将数据框转换为多索引系列
【发布时间】:2019-04-14 06:28:53
【问题描述】:

我有以下数据框:

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() 也没有帮助(或者我可能没有使用它)。

【问题讨论】:

    标签: python python-3.x pandas dataframe series


    【解决方案1】:

    使用set_indexstackrename_axis 来设置新的索引名称:

    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分钟:)
    • 无论如何我可以命名该列,以便将所有这些列作为索引,即如何将其转换为多索引系列?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 2017-02-23
    • 2022-01-24
    • 2017-10-23
    • 2021-12-08
    • 2021-12-17
    相关资源
    最近更新 更多