Home > Blockchain >  How to transpose and Pandas DataFrame and name new columns?
How to transpose and Pandas DataFrame and name new columns?

Time:01-22

I have simple Pandas DataFrame with 3 columns. I am trying to Transpose it into and then rename that new dataframe and I am having bit trouble.

df = pd.DataFrame({'TotalInvoicedPrice': [123],
               'TotalProductCost': [18],
               'ShippingCost': [5]})

I tried using

df =df.T

which transpose the DataFrame into:

TotalInvoicedPrice,123
TotalProductCost,18
ShippingCost,5

So now i have to add column names to this data frame "Metrics" and "Values" I tried using df.columns["Metrics","Values"] but im getting errors. What I need to get is DataFrame that looks like:

  Metrics            Values
0 TotalInvoicedPrice 123
1 TotalProductCost    18
2 ShippingCost         5

CodePudding user response:

Let's reset the index then set the column labels

df.T.reset_index().set_axis(['Metrics', 'Values'], axis=1)

              Metrics  Values
0  TotalInvoicedPrice     123
1    TotalProductCost      18
2        ShippingCost       5

CodePudding user response:

Maybe you can avoid transpose operation (little performance overhead)

#YOUR DATAFRAME
df = pd.DataFrame({'TotalInvoicedPrice': [123],
               'TotalProductCost': [18],
               'ShippingCost': [5]})

#FORM THE LISTS FROM YOUR COLUMNS AND FIRST ROW VALUES
l1 = df.columns.values.tolist()
l2 = df.iloc[0].tolist()

#CREATE A DATA FRAME.
df2 = pd.DataFrame(list(zip(l1, l2)),columns = ['Metrics', 'Values'])

print(df2)
  • Related