PedroA
PedroA

Reputation: 1925

Reshape rows to columns in pandas dataframe

In pandas how to go from a:

a = pd.DataFrame({'foo': ['m', 'm', 'm', 's', 's', 's'],
                    'bar': [1, 2, 3, 4, 5, 6]})
>>> a
   bar foo
0    1   m
1    2   m
2    3   m
3    4   s
4    5   s
5    6   s

to b:

b = pd.DataFrame({'m': [1, 2, 3],
                    's': [4, 5, 6]})
>>> b
   m  s
0  1  4
1  2  5
2  3  6

I tried solutions in other answers, e.g. here and here but none seemed to do what I want.

Basically, I want to swap rows with columns and drop the index, but how to do it?

Upvotes: 7

Views: 1966

Answers (2)

BENY
BENY

Reputation: 323236

This is my solution

a = pd.DataFrame({'foo': ['m', 'm', 'm', 's', 's', 's'],
                    'bar': [1, 2, 3, 4, 5, 6]})
a.pivot(columns='foo', values='bar').apply(lambda x: pd.Series(x.dropna().values))

foo    m    s
0    1.0  4.0
1    2.0  5.0
2    3.0  6.0

Upvotes: 4

piRSquared
piRSquared

Reputation: 294258

a.set_index(
    [a.groupby('foo').cumcount(), 'foo']
).bar.unstack()

Upvotes: 6

Related Questions