python中apply函数

函数原型:

DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)

1.该函数最有用的是第一个参数,这个参数是函数,相当于C/C++的函数指针。
2.这个函数需要自己实现,函数的传入参数根据axis来定,比如axis = 1,就会把一行数据作为Series的数据
结构传入给自己实现的函数中,我们在函数中实现对Series不同属性之间的计算,返回一个结果,则apply函数
会自动遍历每一行DataFrame的数据,最后将所有结果组合成一个Series数据结构
并返回。
3.apply函数常与groupby函数一起使用,如下图所示
在这里插入图片描述
4.举栗子
1.对指定列进行操作

data=np.arange(0,16).reshape(4,4)
data=pd.DataFrame(data,columns=['0','1','2','3'])
def f(x):
    return x-1
print(data)
print(data.ix[:,['1','2']].apply(f))
    0   1   2   3
0   0   1   2   3
1   4   5   6   7
2   8   9  10  11
3  12  13  14  15
    1   2
0   0   1
1   4   5
2   8   9
3  12  13

2.对行操作

data=np.arange(0,16).reshape(4,4)
data=pd.DataFrame(data,columns=['0','1','2','3'])
def f(x):
    return x-1
print(data)
print(data.ix[[0,1],:].apply(f))
    0   1   2   3
0   0   1   2   3
1   4   5   6   7
2   8   9  10  11
3  12  13  14  15
   0  1  2  3
0 -1  0  1  2
1  3  4  5  6
3.整体对列操作
ata=np.arange(0,16).reshape(4,4)
data=pd.DataFrame(data,columns=['0','1','2','3'])
def f(x):
    return x.max()
print(data)
print(data.apply(f))
    0   1   2   3
0   0   1   2   3
1   4   5   6   7
2   8   9  10  11
3  12  13  14  15

0    12
1    13
2    14
3    15
dtype: int64
发布了15 篇原创文章 · 获赞 6 · 访问量 1437

猜你喜欢

转载自blog.csdn.net/qq_39783265/article/details/102838127
今日推荐