-3
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
How wonderful! There’s genius here! Thank you!!!!!!!!
– Maria Lúcia Macieira