1. 程式人生 > >python-pandas的基本用法03

python-pandas的基本用法03

pandas的基本用法03-reindex()

    # -*- coding: utf-8 -*- 
    import numpy as np
    from pandas import DataFrame, Series
    from matplotlib.pyplot import axis

    s = Series([1,2,3,4], index=['a','b','c','d'])
    s2 = s.reindex(['a','b','c','d','e'], fill_value=0)
    print s2
    # a    1
    # b    2
    # c    3
    # d    4
    # e    0
    # dtype: int64
    s2 = s.reindex(['a','b','c','d','e'], method='ffill')
    print s2
    # a    1
    # b    2
    # c    3
    # d    4
    # e    4
    # dtype: int64

    print '對DataFrame重新指定索引'
    f = DataFrame(np.arange(9).reshape(3, 3),
              index = ['i1', 'i2', 'i3'],
              columns = ['c1','c2','c3'])
    print f
    #     c1  c2  c3
    # i1   0   1   2
    # i2   3   4   5
    # i3   6   7   8

    f2 = f.reindex(['a','b','c', 'd'])
    print f2
    #  c1  c2  c3
    # a NaN NaN NaN
    # b NaN NaN NaN
    # c NaN NaN NaN
    # d NaN NaN NaN

    print '重新指定column'
    names = ['c1', 'c2', 'Tony']
    print f.reindex(columns=names)
    #     c1  c2  Tony
    # i1   0   1   NaN
    # i2   3   4   NaN
    # i3   6   7   NaN

    print '對DataFrame重新指定索引並指定填元素充方法'
    print f
    #     c1  c2  c3
    # i1   0   1   2
    # i2   3   4   5
    # i3   6   7   8
    f2 = f.reindex(index=['i1', 'i2', 'x'],
                    method='ffill', columns=names)
    print f2
    #     c1  c2  Tony
    # i1   0   1   NaN
    # i2   3   4   NaN
    # x    6   7   NaN
    print f2.fillna(method='ffill', axis=1)
    #     c1  c2  Tony
    # i1   0   1     1
    # i2   3   4     4
    # x    6   7     7

這裡寫圖片描述