pandas中apply, applymap 和map的用法及区别

1. apply()函数的用法。

DataFrame.apply(func, axis = 0/1),将指定函数应用于dataframe中的行或者列上。官网上提示这个函数在将来会取消。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
frame = DataFrame(np.random.randn(4, 3), columns=list('bde'),
index=['Utah', 'Ohio', 'Texas', 'Oregon'])
b d e
Utah 0.248637 1.583772 -0.630755
Ohio -0.096555 -0.265234 0.545998
Texas -0.097191 -0.200923 -2.147096
Oregon 1.139358 -0.992095 -0.066734
f = lambda x: x.max() - x.min()
frame.apply(f)
b 1.236549
d 2.575866
e 2.693094
dtype: float64
frame.apply(f, axis = 1)
Utah 2.214527
Ohio 0.811232
Texas 2.049906
Oregon 2.131453
dtype: float64

2. applymap(),相比于apply(),其作用范围为整个DataFrame里面的数据。

1
2
3
4
5
6
frame.applymap(lambda x:'%.2f' % x)
b d e
Utah 0.25 1.58 -0.63
Ohio -0.10 -0.27 0.55
Texas -0.10 -0.20 -2.15
Oregon 1.14 -0.99 -0.07

3. map() 作用对象为Series。

1
2
3
4
5
6
7
frame['e'].map(lambda x: '%.2f'% x)
Utah -0.63
Ohio 0.55
Texas -2.15
Oregon -0.07
Name: e, dtype: object