My pd.DataFrame looks like the one as follows:
import pandas as pd
df = pd.DataFrame({"MCD":[1,2,-2,-3, 5],
"AAPL":[-0.3, -0.6, 0.6, 0.9, -1.5],
"GOOG":[-0.8, 1.6, 2.4, 3.6 , -4],
"MSFT":[-0.1, -0.4, 0.8, 1.1, -1.3]})
df
>>>
MCD AAPL GOOG MSFT
0 1 -0.3 -0.8 -0.1
1 2 -0.6 1.6 -0.4
2 -2 0.6 2.4 0.8
3 -3 0.9 3.6 1.1
4 5 -1.5 -4.0 -1.3
I want my dataframe to look like this by using the method .melt
.
desired_df
>>>
ticker return
0 MCD 1
1 MCD 2
2 MCD -2
3 MCD -3
4 MCD 5
5 AAPL -0.3
6 AAPL -0.6
7 AAPL 0.6
....
18 MSFT 1.1
19 MSFT -1.3
How can I turn my df
to desired_df
using the method .melt
?
p.s. One doesn't need to use .melt
if there is a better way to answer my question. To me, .melt
seems to be a good solution to answer my question so I just used it as an example method. :D
p.s2. My question was closed because someone claimed that there were similar questions. However, those questions do not answer my questions specifically. So I thought my question deserved to be not deleted.