dark horse
dark horse

Reputation: 447

Pandas - Performing a transpose of multiple columns

I have a Dataframe as below:

col1,col2,col3,col4
value1,value2,value3,value4

I am trying to perform a transpose function on them to get the below output:

col1,value1
col2,value2
col3,value3
col4,value4

The problem is the list of columns are dynamic and it depends on user input that pulls the respective columns at the first place.

Use the below query to get the list of columns the user has requested:

cursor.execute('select {} from table'.format(', '.join(str(cols) for cols in col_names)))

Could anyone advice how I could perform a transpose of such a dataframe that has multiple columns but just one row of output. Thanks..

Upvotes: 1

Views: 290

Answers (1)

Karn Kumar
Karn Kumar

Reputation: 8816

If your dataframe construct is the way you have shown in your post with the multiple columns and single row then simply set the index to your first column, in your case its "col1" and then transpose it.

DataFrame as per shown:

df = pd.DataFrame({ 'col1':['value1'], 'col2':['value2'], 'col3':['value2'], 'col4':['value4']})

     col1    col2    col3    col4
0  value1  value2  value2  value4

You can perform like below:

>>> df.set_index('col1',inplace=True) # First set the Index to `col1` + `inplace=True`

Now allow transpose ..

>>> df.T
col1  value1
col2  value2
col3  value2
col4  value4

In one go all :

>>> df.set_index('col1').T
col1  value1
col2  value2
col3  value2
col4  value4

Note: df.T will not do the Job because it seeks the default index ie zero in this case to be as columns.

Hope this will help you going.

Upvotes: 1

Related Questions