Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 832
PedroA Avatar asked Jun 17 '17 22:06

PedroA


People also ask

How do I convert rows to columns in Pandas?

The transpose() function is used to transpose index and columns. Reflect the DataFrame over its main diagonal by writing rows as columns and vice-versa.

How do I reshape Pandas DataFrame in Python?

To reshape the dataframe from long to wide in Pandas, we can use Pandas' pd. pivot() method. columns : Column to use to make new frame's columns (e.g., 'Year Month'). values : Column(s) to use for populating new frame's values (e.g., 'Avg.

How do you reshape in DF?

You can use the following basic syntax to convert a pandas DataFrame from a wide format to a long format: df = pd. melt(df, id_vars='col1', value_vars=['col2', 'col3', ...]) In this scenario, col1 is the column we use as an identifier and col2, col3, etc.

How do I turn a row into a column in Python?

columns() to Convert Row to Column Header. You can use df. columns=df. iloc[0] to set the column labels by extracting the first row.


2 Answers

a.set_index(
    [a.groupby('foo').cumcount(), 'foo']
).bar.unstack()
like image 72
piRSquared Avatar answered Sep 25 '22 16:09

piRSquared


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
like image 33
BENY Avatar answered Sep 25 '22 16:09

BENY