I have a dataframe, I want to transpose the rows and columns and change the name of columns as follow. My dataframe is:
import pandas as pd
df = pd.DataFrame()
df ['time'] = [1,2,3,4]
df ['a'] = [3,-1,0, 23]
df['b'] = [-1, 2, 5, 6]
df
I want to change it to the following:
Could you please help me with that?
CodePudding user response:
Transpose and rename would be what you want as this code.
df.T.rename(columns={0:'val 0', 1:'val 1', 2:'val 2', 3:'val 3'}, index={'time':0, 'a':1, 'b':2})
CodePudding user response:
This is a manual way to insert the columns and indexes' names.
header = ["val_0", "val_2", "val_3", "val_4"]
index = range(len(df.columns))
df=df.T
df.columns=header
df.index=index
df
val_0 val_2 val_3 val_4
0 1 2 3 4
1 3 -1 0 23
2 -1 2 5 6