python-pandas的基本用法06

pandas的基本用法06-算术和数据对齐

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

    s1 = Series([-1,3,4], index=['a','b','c'])
    s2 = Series([0,9,2,5], index=['a','b','c','d'])

    print s1+s2
    # a    -1
    # b    12
    # c     6
    # d   NaN
    # dtype: float64

    print 'DataFrame加法'
    df1 = DataFrame(np.arange(9).reshape(3,3),
              index=list('abc'),
              columns=list('123')
              )
    df2 = DataFrame(np.arange(9).reshape(3,3),
              index=list('abd'),
              columns=list('023')
              )

    print df1
    print df2
    print df1+df2
    #    1  2  3
    # a  0  1  2
    # b  3  4  5
    # c  6  7  8
    #    +
    #    0  2  3
    # a  0  1  2
    # b  3  4  5
    # d  6  7  8
    #    =
    #     0   1   2   3
    # a NaN NaN   2   4
    # b NaN NaN   8  10
    # c NaN NaN NaN NaN
    # d NaN NaN NaN NaN

    print '数据填充'
    df1 = DataFrame(np.arange(12.).reshape(3,4))
    df2 = DataFrame(np.arange(20.).reshape(4,5))
    print df1
    #    0  1   2   3
    # 0  0  1   2   3
    # 1  4  5   6   7
    # 2  8  9  10  11
    print df2
    #     0   1   2   3   4
    # 0   0   1   2   3   4
    # 1   5   6   7   8   9
    # 2  10  11  12  13  14
    # 3  15  16  17  18  19
    print df1.add(df2)
    #     0   1   2   3   4
    # 0   0   2   4   6 NaN
    # 1   9  11  13  15 NaN
    # 2  18  20  22  24 NaN
    # 3 NaN NaN NaN NaN NaN
    print df1.add(df2, fill_value=0)
    #     0   1   2   3   4
    # 0   0   2   4   6   4
    # 1   9  11  13  15   9
    # 2  18  20  22  24  14
    # 3  15  16  17  18  19
    print df1.reindex(columns=df2.columns, fill_value=0)
    #    0  1   2   3  4
    # 0  0  1   2   3  0
    # 1  4  5   6   7  0
    # 2  8  9  10  11  0

    print 'DataFrame与Series之间的操作'

    dataframe = DataFrame(np.arange(12.).reshape(3,4))
    series = dataframe.ix[0]
    print dataframe
    #    0  1   2   3
    # 0  0  1   2   3
    # 1  4  5   6   7
    # 2  8  9  10  11
    print series
    # 0    0
    # 1    1
    # 2    2
    # 3    3
    print dataframe-series
    #    0  1  2  3
    # 0  0  0  0  0
    # 1  4  4  4  4
    # 2  8  8  8  8
    series = dataframe[0]
    print dataframe.sub(series, axis=0)# 按列减
    #    0  1  2  3
    # 0  0  1  2  3
    # 1  0  1  2  3
    # 2  0  1  2  3

你可能感兴趣的:(python)