1

I am struggling with the following: I have on dataset and have transposed it. After transposing, the first column was set as an index automatically, and from now one, this "index" column is not recognized as a variable. Here is an example of what I mean;

df =     Date     A B C
       1/1/2021   1 2 3
       1/2/2021   4 5 6

input:   df_T = df.t
output:  index 1/1/2021 1/2/2021 
           A        1      4
           B        2      5
           C        3      6

I would like to have a variable, and name if it is possible, instead of the generated "index".

1
  • 3
    Generally, one can reset the index which will make it a column df.reset_index(inplace=True). I think that's what you're looking for. Commented Dec 19, 2021 at 17:36

2 Answers 2

1

To reproduce this dataset, I have used this chunk of code:

data = [['1/1/2021', 1, 2, 3], ['3/1/2021', 4, 5, 6]]
df = pd.DataFrame(data)
df.columns = ['Date', 'A', 'B', 'C']
df.set_index('Date', inplace=True)

To have meaningfull column inplace of index, the next line can be run:

df_T = df.T.reset_index()

To rename the column 'index', method rename can be used:

df_T.rename(columns={'index':'Variable'})
Sign up to request clarification or add additional context in comments.

Comments

1

A Pandas Data Frame typically has names both for the colmns and for the rows. The list of names for the rows is called the "Index". When you do a transpose, rows and columns switch places. In your case, the dates column is for some reason the index, so it becomes the column names for the new data frame. You need to create a new index and turn the "Date" column into a regular column. As @sophocies wrote above, this is achived with df.reset_index(...). I hope the code example below will be helpful.

import pandas as pd
df = pd.DataFrame(columns=['Date', 'A', 'B', 'C'], data=[['1/1/2021', 1, 2,3], ['1/2/2021', 4,5,6]])
df.set_index('Date', inplace=True)
print(df.transpose(copy=True))
#Recreated the problem
df.reset_index(inplace=True)
print(df.transpose())

Output

0 1
Date 1/1/2021 1/2/2021
A 1 4
B 2 5
C 3 6

I hope this is what you wanted!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.