Skip to main content
 首页 » 编程设计

python之取消展平数据框中的行

2025年05月04日14Leo_wl

使用这样的数据框:

date           user    sales_blue     sales_red 
2019/06/01        A            30            50 
2019/06/01        B            60            70 
2019/06/02        A            25            35 
2019/06/02        B            42            52 

我正在努力做到以下几点:

date           user    color    sales 
2019/06/01        A     blue       30 
2019/06/01        A      red       50 
2019/06/01        B     blue       60 
2019/06/01        B      red       70 
2019/06/02        A     blue       25 
2019/06/02        A      red       35 
2019/06/02        B     blue       42 
2019/06/02        B      red       52 

这通过使用循环以一种“手动”方式相当可行,但出于性能原因,我会寻找一种不涉及 Python 循环的更有效的解决方案。

请您参考如下方法:

当您想使用列名的所有 来标识行时,melt 通常是首选。但是,当您想要使用列名称的较小部分时,其中前缀是常量,melt 的通用、更用户友好的版本称为 wide_to_long。

这不仅可以干净地处理前缀,还可以扩展以处理多个不同的前缀。

pd.wide_to_long( 
    df, stubnames='sales', i=['date', 'user'], j='color', suffix='\w+', sep='_' 
).reset_index(-1) 

                color  sales 
user date 
A    2019/06/01  blue     30 
     2019/06/01   red     50 
B    2019/06/01  blue     60 
     2019/06/01   red     70 
A    2019/06/02  blue     25 
     2019/06/02   red     35 
B    2019/06/02  blue     42 
     2019/06/02   red     52 

将此行为概括为熔化多个列:

print(df) 
 
         date user  sales_blue  sales_red  calls_blue  calls_red 
0  2019/06/01    A          30         50           3          4 
1  2019/06/01    B          60         70           1          2 
2  2019/06/02    A          25         35           4          6 
3  2019/06/02    B          42         52           5          7 

pd.wide_to_long( 
  df, stubnames=['sales', 'calls'], i=['date', 'user'], j='color', suffix='\w+', sep='_' 
).reset_index(-1) 

                color  sales  calls 
date       user 
2019/06/01 A     blue     30      3 
           A      red     50      4 
           B     blue     60      1 
           B      red     70      2 
2019/06/02 A     blue     25      4 
           A      red     35      6 
           B     blue     42      5 
           B      red     52      7