美文网首页
12.数据透视

12.数据透视

作者: B0ZZ | 来源:发表于2019-02-10 13:28 被阅读0次

    0.背景

    • stack将数据列旋转为行,unstack将数据的行旋转为列;
    • pivot重塑的一个快捷方式。index,重塑的索引;columns,重塑的列名;values,生成新列的值;

    1.stack & unstack

    import numpy as np
    import pandas as pd
    data = pd.DataFrame(np.arange(4*5).reshape((4,5)),
                        index=pd.Index(['beijing','shanghai','guangzhou','shenzhen'],name='city'),
                        columns=pd.Index(['one','two','three','four','five'],name='number'))
    print data
    
    data
    result_stack = data.stack(dropna=False)
    print result_stack
    
    result_stack.png
    result_unstack = result_stack.unstack('city')
    print result_unstack
    
    result_unstack.png

    2.pivot(目前在数据处理过程中,pivot不是必要的)

    import numpy as np
    import pandas as pd
    data = pd.DataFrame(np.arange(4*5).reshape((4,5)),
                        index=pd.Index(['beijing','shanghai','guangzhou','shenzhen'],name='city'),
                        columns=pd.Index(['one','two','three','four','five'],name='number'))
    result_pivot = data.pivot('one','two')
    print result_pivot
    
    result_pivot.png

    相关文章

      网友评论

          本文标题:12.数据透视

          本文链接:https://www.haomeiwen.com/subject/vmwteqtx.html