• pandas.DataFrame.unstack抄书笔记


    pandas.DataFrame.unstack

    DataFrame.unstack(level=1fill_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
    

      

  • 相关阅读:
    C#读取Excel文档
    用DataSet方式更新数据库表
    using(){},Close(),Dispose()的区别
    ADO.NET连接数据库的两种方式
    DateUtils
    GoF的23个经典设计模式
    react中需要用到【深度复制】的问题
    css区分ie8/ie9/ie10/ie11 chrome firefox的代码
    【个人学习笔记】走近H5
    【React入门实例(运行于浏览器duan)】
  • 原文地址:https://www.cnblogs.com/sidianok/p/14480871.html
Copyright © 2020-2023  润新知