python-pandas的基本用法07

来源:互联网 发布:网络机柜检验报告 编辑:程序博客网 时间:2024/06/05 06:35

pandas的基本用法07-匿名函数

    # -*- coding: utf-8 -*-     import numpy as np    from pandas import Series, DataFrame    from pandas.core.format import DataFrameFormatter    print 'lambda以及应用'    frame = DataFrame(np.random.randn(3,4),                      index=list('abc'),columns=[1,2,3,4]                      )    print frame    #           1         2         3         4    # a  1.099778 -0.953612  0.776224 -0.751771    # b  0.094904 -0.882894 -0.689881 -0.694949    # c  1.329955  0.137261  2.276389  0.546899    f = lambda x:x.max()-x.min()    # apply() 和applymap()是DataFrame数据类型的函数    # applymap()是element-wise的,作用于每个DataFrame的每个数据。     # map()是Series数据类型的函数,也是element-wise的,对Series中的每个数据调用一次函数。​    print frame.apply(f, axis=1)#按行减    # a    2.680024    # b    3.077474    # c    1.255980    _format = lambda x: '%.2f'%x    print frame.applymap(_format)    #        1      2      3      4    # a  -0.23  -1.47  -0.16   0.40    # b   0.21   0.94  -0.22  -3.51    # c  -0.30  -0.35  -0.25   0.76    print frame[1].map(_format)    # a    0.63    # b    0.51    # c    0.11
原创粉丝点击