I have the dataframe
Acatis TrueValue ValorRelativo
Date
2015-12-29 220.43 12.959 12.311
2020-05-13 270.27 12.870 13.234
I need to transform it into this other one.
Nombre Date Close
0 Acatis 2015-12-29 220.430
1 Acatis 2020-05-13 270.270
2 TrueValue 2015-12-29 12.959
3 TrueValue 2020-05-13 12.870
4 ValorRelativo 2015-12-29 12.311
5 ValorRelativo 2020-05-13 13.234
Is it possible to do it by applying some method/s?
Indeed, using "melt" it can be done like this:
p1 = pd.melt(df_analisis, id_vars =['Date'], value_vars =['Acatis'])
p2 = pd.melt(df_analisis, id_vars =['Date'], value_vars =['TrueValue'])
p3 = pd.melt(df_analisis, id_vars =['Date'], value_vars =['ValorRelativo'])
datos = pd.concat([p1, p2, p3], join="inner")
datos
The output is:
Date variable value
0 2015-12-29 Acatis 220.430
1 2020-05-13 Acatis 270.270
0 2015-12-29 TrueValue 12.959
1 2020-05-13 TrueValue 12.870
0 2015-12-29 ValorRelativo 12.311
1 2020-05-13 ValorRelativo 13.234
Is there a more direct way?
I think what you are looking for is a function called
melt
, which is present in the Pandas library.Here is the link to the documentation:
[1] https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html
The solution would be something like this: