df unstack

Solutions on MaxInterview for df unstack by the best coders in the world

showing results for - "df unstack"
Quintrell
24 Apr 2017
1>>> index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'),
2...                                    ('two', 'a'), ('two', 'b')])
3>>> s = pd.Series(np.arange(1.0, 5.0), index=index)
4>>> s
5one  a   1.0
6     b   2.0
7two  a   3.0
8     b   4.0
9dtype: float64
10
11s.unstack(level=-1)
12     a   b
13one  1.0  2.0
14two  3.0  4.0
15
16s.unstack(level=0)
17   one  two
18a  1.0   3.0
19b  2.0   4.0
20
21df = s.unstack(level=0)
22df.unstack()
23one  a  1.0
24     b  2.0
25two  a  3.0
26     b  4.0
27dtype: float64
Jacobo
29 Feb 2017
1import pandas as pd
2import numpy as np
3arrays = [['Monday','Monday','Tursday','Tursday'],
4                        ['Morning','Noon','Morning','Evening']]
5tuples = list(zip(*arrays))
6index = pd.MultiIndex.from_tuples(tuples, names=['Weekday', 'Time'])
7df = pd.DataFrame(np.random.randint(5, size=(4,2)), index=index)
8
9In [39]: df
10Out[39]: 
11                 0  1
12Weekday Time         
13Monday  Morning  1  3
14        Noon     2  1
15Tursday Morning  3  3
16        Evening  1  2
17
18In [40]: pd.DataFrame(df.to_records())
19Out[40]: 
20   Weekday     Time  0  1
210   Monday  Morning  1  3
221   Monday     Noon  2  1
232  Tursday  Morning  3  3
243  Tursday  Evening  1  2
25