sayo
sayo

Reputation: 217

I want to reshape a dataframe to look differently such that the rows become columns but unable to do so

My data frame looks like this :

import pandas as pd
df = pd.DataFrame({'0':['USA'],
                   '1':['UK'],
                   '2':['UAE']})

I want the reshaped dataframe to look like this:

df1 = pd.DataFrame({'Country':['USA','UK','UAE'],
                   'Prob':['0','1','2']})

Upvotes: 1

Views: 52

Answers (3)

Wassermann
Wassermann

Reputation: 245

Using values attribute you can extract underlying numpy array storing actual data of your DataFrame and use it to build a new DataFrame. ravel() function flattens original 2D array with a single row to 1D array so that you can build a column out of it. The whole DataFrame can be built as follows:

df1 = pd.DataFrame({'Country':df.values.ravel(), 'Prob':df.columns.values})

Upvotes: 1

Andy L.
Andy L.

Reputation: 25239

Try transpose, assign, and rename

df.T.assign(Prob=df.columns).rename(columns={0: 'Country'})

Out[63]:
  Country Prob
0     USA    0
1      UK    1
2     UAE    2

Upvotes: 0

sayo
sayo

Reputation: 217

I have achieved it in this way but i was wondering if there is a way to do it with melt and reshape:

cols1 = df.iloc[0]

df_cols1 = pd.DataFrame({'Country':cols1})

cols2 = list(df.columns)

df_cols2 = pd.DataFrame({'Prob':cols2})

df_cols1.reset_index(drop=True, inplace=True)

df_cols2.reset_index(drop=True, inplace=True)

df1 = pd.concat([df_cols1,df_cols2], axis=1)

Upvotes: 0

Related Questions