Redge
Redge

Reputation: 13

Pandas: Reshape two columns into one row

I want to reshape a pandas DataFrame from two columns into one row:

import numpy as np
import pandas as pd
df_a = pd.DataFrame({ 'Type': ['A', 'B', 'C', 'D', 'E'], 'Values':[2,4,7,9,3]})
df_a

   Type Values
0   A   2
1   B   4
2   C   7
3   D   9
4   E   3

df_b = df_a.pivot(columns='Type', values='Values')
df_b

Which gives me this:

Type A       B       C       D      E
0   2.0     NaN     NaN     NaN     NaN
1   NaN     4.0     NaN     NaN     NaN
2   NaN     NaN     7.0     NaN     NaN
3   NaN     NaN     NaN     9.0     NaN
4   NaN     NaN     NaN     NaN     3.0

When I want it condensed into a single row like this:

Type A       B       C       D      E
0   2.0     4.0     7.0     9.0     3.0

Upvotes: 1

Views: 670

Answers (3)

BENY
BENY

Reputation: 323326

We can fix your df_b

df_b.ffill().iloc[[-1],:]
Out[360]: 
Type    A    B    C    D    E
4     2.0  4.0  7.0  9.0  3.0

Or we do

df_a.assign(key=[0]*len(df_a)).pivot(columns='Type', values='Values',index='key')
Out[366]: 
Type  A  B  C  D  E
key                
0     2  4  7  9  3

Upvotes: 0

jezrael
jezrael

Reputation: 863166

I believe you dont need pivot, better is DataFrame constructor only:

df_b = pd.DataFrame([df_a['Values'].values], columns=df_a['Type'].values)
print (df_b)
   A  B  C  D  E
0  2  4  7  9  3

Or set_index with transpose by T:

df_b = df_a.set_index('Type').T.rename({'Values':0})
print (df_b)
Type  A  B  C  D  E
0     2  4  7  9  3

Upvotes: 1

YOLO
YOLO

Reputation: 21739

Another way:

df_a['col'] = 0
df_a.set_index(['col','Type'])['Values'].unstack().reset_index().drop('col', axis=1)

Type    A   B   C   D   E
  0     2   4   7   9   3

Upvotes: 0

Related Questions