Как сделать индекс pandas сводной таблицы частью имен столбцов?

Я пытаюсь развернуть два столбца другим столбцом флага без мультииндексации. Я хотел бы, чтобы имена столбцов были частью самого индикатора. Возьмем, к примеру:

import pandas as pd
df_dict = {'fire_indicator':[0,0,1,0,1],
           'cost':[200, 300, 354, 456, 444],
           'value':[1,1,2,1,1],
           'id':['a','b','c','d','e']}
df = pd.DataFrame(df_dict) 

Если я сделаю следующее:

df.pivot_table(index = 'id', columns = 'fire_indicator', values = ['cost','value'])

Я получаю следующее:

                 cost        value     
fire_indicator      0      1     0    1
id                                     
a               200.0    NaN   1.0  NaN
b               300.0    NaN   1.0  NaN
c                 NaN  354.0   NaN  2.0
d               456.0    NaN   1.0  NaN
e                 NaN  444.0   NaN  1.0

Я пытаюсь сделать следующее:

id    fire_indicator_0_cost    fire_indicator_1_cost    fire_indicator_0_value    fire_indicator_0_value
a               200                      0                          1                        0
b               300                      0                          1                        0
c                0                      354                         0                        2
d               456                      0                          1                        0
e                0                      444                         0                        1

Я знаю, что есть способ в SAS. Есть ли способ в питоне pandas?

0
0
270
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Просто переименуйте и пере_индексируйте:

out = df.pivot_table(index = 'id', columns = 'fire_indicator', values = ['cost','value'])

out.columns = [f'fire_indicator_{y}_{x}' for x,y in out.columns]

# not necessary if you want `id` be the index
out = out.reset_index()

Выход:

    id      fire_indicator_0_cost    fire_indicator_1_cost    fire_indicator_0_value    fire_indicator_1_value
--  ----  -----------------------  -----------------------  ------------------------  ------------------------
 0  a                         200                      nan                         1                       nan
 1  b                         300                      nan                         1                       nan
 2  c                         nan                      354                       nan                         2
 3  d                         456                      nan                         1                       nan
 4  e                         nan                      444                       nan                         1

Другие вопросы по теме