python - Pandas 转换多索引头

标签 python pandas dataframe

我有一个具有以下格式的数据框:

        price                cost              
   id   mean   max    min    mean   max    min  
    0     1     1      1       1     2      3
    1     2     2      2       1     2      3
    2     3     3      3       1     2      3

我想将其更改为以下内容:

   id      mean   max    min    type
    0       1     1      1     price    
    1       2     2      2     price  
    2       3     3      3     price
    0       1     1      1     cost       
    1       2     2      2     cost   
    2       3     3      3     cost 

最佳答案

尝试使用 stack() 方法、drop() 方法、reset_index() 方法和 rename() 方法:

df=(df.stack(0)
 .drop('id',1)
 .reset_index()
 .rename(columns={'level_0':'id','level_1':'type'}))

df 的输出:

    id  type    max     mean    min
0   0   cost    2       1       1
1   0   price   1       1       3
2   1   cost    2       1       2
3   1   price   2       2       3
4   2   cost    2       1       3
5   2   price   3       3       3

关于python - Pandas 转换多索引头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67578933/

相关文章:

python - 如何根据 python 数据框中的行条件查找最接近的列名称?

python - 如何根据数据框中的相似行(字符串)删除数据框的某些行

dataframe - Julia - 选择以另一个数据帧中的列为条件的数据帧的子集

python - 将长度为 n 的字符串读取为 pandas 中的 n 列

r - 我如何计算不同组的列的值?

python - Django 相关领域总是仅在生产中抛出完整性错误

python - 如何使用discord.py创建 "react to role"嵌入消息

python - 对数据帧列执行按位运算(|、&)

python - 对数时间Python中有序列表中的位置元素

python - scipy.optimize.minimize 忽略约束