Python Dataframe to convert column name as row value
Question:
I am very new to python. Could you please provide me solution?
I have the input like this:
Calendar X Y
0 2020-01-01 10 22
1 2020-02-01 15 45
2 2020-03-01 13 67
3 2020-04-01 33 89
Expected output is :
Type Calendar Act_Value
X 2020-01-01 10
X 2020-02-01 15
X 2020-03-01 13
X 2020-04-01 33
Y 2020-01-01 22
Y 2020-02-01 45
Y 2020-03-01 67
Y 2020-04-01 89
Answers:
Like @GodWin mentioned, pd.melt()
is a way to do this. This is from the pandas
module which is the most popular data tool in Python. You can get more information from https://pandas.pydata.org/, and here is a quick suggestion on how you can achieve your output.
## import module
import pandas as pd
## create data frame
df = pd.DataFrame({
"Calendar":["2020-01-01","2020-02-01","2020-03-01","2020-04-01"],
"X":[10,15,13,33],
"Y":[22,45,67,89]})
## output
print(pd.melt(df, id_vars="Calendar", var_name="Type",value_name="Act_value"))
#################################
Calendar Type Act_value
0 2020-01-01 X 10
1 2020-02-01 X 15
2 2020-03-01 X 13
3 2020-04-01 X 33
4 2020-01-01 Y 22
5 2020-02-01 Y 45
6 2020-03-01 Y 67
7 2020-04-01 Y 89
import numpy as np
import pandas as pd
df = pd.DataFrame([{"Calendar": "2020-01-01", "X": 10, "Y": 22}, {"Calendar":
"2020-02-01", "X": 15, "Y": 45}, {"Calendar": "2020-03-01", "X": 13, "Y": 67},
{"Calendar": "2020-04-01", "X":33, "Y": 89}])
df_unpivoted = df.melt(id_vars=['Calendar'], var_name='Type',
value_name='Act_value')
df_unpivoted.set_index('Type')
I am very new to python. Could you please provide me solution?
I have the input like this:
Calendar X Y
0 2020-01-01 10 22
1 2020-02-01 15 45
2 2020-03-01 13 67
3 2020-04-01 33 89
Expected output is :
Type Calendar Act_Value
X 2020-01-01 10
X 2020-02-01 15
X 2020-03-01 13
X 2020-04-01 33
Y 2020-01-01 22
Y 2020-02-01 45
Y 2020-03-01 67
Y 2020-04-01 89
Like @GodWin mentioned, pd.melt()
is a way to do this. This is from the pandas
module which is the most popular data tool in Python. You can get more information from https://pandas.pydata.org/, and here is a quick suggestion on how you can achieve your output.
## import module
import pandas as pd
## create data frame
df = pd.DataFrame({
"Calendar":["2020-01-01","2020-02-01","2020-03-01","2020-04-01"],
"X":[10,15,13,33],
"Y":[22,45,67,89]})
## output
print(pd.melt(df, id_vars="Calendar", var_name="Type",value_name="Act_value"))
#################################
Calendar Type Act_value
0 2020-01-01 X 10
1 2020-02-01 X 15
2 2020-03-01 X 13
3 2020-04-01 X 33
4 2020-01-01 Y 22
5 2020-02-01 Y 45
6 2020-03-01 Y 67
7 2020-04-01 Y 89
import numpy as np
import pandas as pd
df = pd.DataFrame([{"Calendar": "2020-01-01", "X": 10, "Y": 22}, {"Calendar":
"2020-02-01", "X": 15, "Y": 45}, {"Calendar": "2020-03-01", "X": 13, "Y": 67},
{"Calendar": "2020-04-01", "X":33, "Y": 89}])
df_unpivoted = df.melt(id_vars=['Calendar'], var_name='Type',
value_name='Act_value')
df_unpivoted.set_index('Type')