python - 将两列数据框转换为多索引系列

标签 python pandas dataframe series

如何转动此数据框:

In [1]: df
Out[1]:
col_name         C    P
FULL  count_x    1    5
      count_y    2    6
CALIB count_x    3    7
      count_y    4    8

进入本系列:

In [2]: s
Out[2]:    
C  FULL  count_x    1
         count_y    2
   CALIB count_x    3
         count_y    4
P  FULL  count_x    5
         count_y    6
   CALIB count_x    7
         count_y    8

Python 3、Pandas 1.1.1。

最佳答案

使用DataFrame.unstack按两个级别:

s = df.unstack([0,1])
print (s)
C  FULL      count_x    1
             count_y    2
   CALIB     count_x    3
             count_y    4
P  FULL      count_x    5
             count_y    6
   CALIB     count_x    7
             count_y    8
dtype: int64

另一个想法 DataFrame.stack ,但需要进行其他处理 - Series.reorder_levelsSeries.sort_index :

s = df.stack().reorder_levels([2,0,1]).sort_index()
print (s)
   col_name         
C  CALIB     count_x    3
             count_y    4
   FULL      count_x    1
             count_y    2
P  CALIB     count_x    7
             count_y    8
   FULL      count_x    5
             count_y    6
dtype: int64

关于python - 将两列数据框转换为多索引系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64390040/

相关文章:

python - 获取列表中具有相同最大值的最后一个索引

python - 在一行中分配多个变量

python - pandas - 按列名屏蔽数据框

python - 导入请求在 Python 3.7 中不起作用

python - 拼写错误,Python 函数仍然有效。为什么?

python - 如何强制 Pandas dataframe 列查询仅返回 str 而不解释它所看到的内容?

python - 在 Python 中使用 != 运算符删除行不起作用

python - 从列表创建数据框

python - 如何在 python 中比较数据框中的两个字符串列表是否有任何匹配项以获得 True 或 False?

r - 创建一个包含一行和多列的数据框