pandas.DataFrame.unstack抄书笔记
pandas.DataFrame.unstack¶
DataFrame.
unstack
(level=- 1, fill_value=None)[source]-
Pivot a level of the (necessarily hierarchical) index labels.
Returns a DataFrame having a new level of column labels whose inner-most level consists of the pivoted index labels.
If the index is not a MultiIndex, the output will be a Series (the analogue of stack when the columns are not a MultiIndex).
- Parameters
- levelint, str, or list of these, default -1 (last level)
-
Level(s) of index to unstack, can pass level name.
- fill_valueint, str or dict
-
Replace NaN with this value if the unstack produces missing values.
- Returns
- Series or DataFrame
这是一个有意思的方法,实在很有意思。unstack,当dataframe对象是有一个多层index的时候,会从index中抽出去,填补到columns中去,
如果一个多层index的Series,就会变成了DataFrame对象。
如果是一个单层的index的DataFrame对象,[如果列的索引是多层索引],则会返回一个Series对象,列索引变成行索引的多层索引的第一层。
Example
index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'), ('two', 'a'), ('two', 'b')]) s = pd.Series(np.arange(1.0, 5.0), index=index) s
one a 1.0
b 2.0
two a 3.0
b 4.0
dtype: float64
In [12]: s Out[12]: one a 1.0 b 2.0 two a 3.0 b 4.0 dtype: float64 In [13]: s.unstack() Out[13]: a b one 1.0 2.0 two 3.0 4.0 In [14]: s.unstack(-1) Out[14]: a b one 1.0 2.0 two 3.0 4.0 In [15]: s.unstack(0) Out[15]: one two a 1.0 3.0 b 2.0 4.0