Turn a column into several other columns into a pandas data frame

Asked

Viewed 48 times

-3

Good morning! I need a help... I’ve tried several commands but I think I’m going a long way. I have this dataframe: inserir a descrição da imagem aqui

And I need to turn this: inserir a descrição da imagem aqui

1 answer

0


First add a column with a constant value, then use pivot_table (we need the column with constant value because to pivot we need a column with the values to be filled in the resulting table).

Example:

df = pd.DataFrame({
    "Nome Fundo": ['FUNDO AAA', 'FUNDO AAA', 'FUNDO AAA', 'FUNDO BBB', 'FUNDO CCC'], 
    'data competencia': ['02-2021', '03-2021', '04-2021', '03-2021', '01-2021']
})

df["constante"] = 1
resultado = df.pivot_table(
    values="constante", 
    index="Nome Fundo", 
    columns="data competencia",
)

print(resultado)

output (see that pivot_table fills the missing combinations in the constant column with NaN):

data competencia  01-2021  02-2021  03-2021  04-2021
Nome Fundo                                          
FUNDO AAA             NaN      1.0      1.0      1.0
FUNDO BBB             NaN      NaN      1.0      NaN
FUNDO CCC             1.0      NaN      NaN      NaN

Browser other questions tagged

You are not signed in. Login or sign up in order to post.