将一个自定义的函数应用到Pandas的数据结构中可以使用map(), apply()或者applymap(),它们的区别在于应用的对象不同。
apply()和applymap()是DataFrame结构中的函数,Series中没有。它们的区别在于,apply()将一个函数作用于DataFrame中的每个行或者列,而applymap()是将函数做用于DataFrame中的所有元素(elements)。
apply() 当想让方程作用在一维的向量上时,可以使用apply来完成
In [6]: from <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/pandas" title="View all posts in pandas" target="_blank">pandas</a></span> import DataFrame In [7]: import numpy as np In [8]: frame = DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['Ut ...: ah', 'Ohio', 'Texas', 'Oregon']) In [9]: frame Out[9]: b d e Utah 1.646124 -0.843271 -0.253782 Ohio -0.965261 0.254368 -0.173054 Texas -0.927661 -0.558319 -0.838144 Oregon -1.410459 -1.901251 1.199630 In [10]: f = lambda x: x.max() - x.min() In [11]: frame.apply(f) Out[11]: b 3.056583 d 2.155619 e 2.037774 dtype: float64
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
In
[
6
]
:
from
pandas
import
DataFrame
In
[
7
]
:
import
numpy
as
np
In
[
8
]
:
frame
=
DataFrame
(
np
.
random
.
randn
(
4
,
3
)
,
columns
=
list
(
'bde'
)
,
index
=
[
'Ut
...: ah'
,
'Ohio'
,
'Texas'
,
'Oregon'
]
)
In
[
9
]
:
frame
Out
[
9
]
:
b
d
e
Utah
1.646124
-
0.843271
-
0.253782
Ohio
-
0.965261
0.254368
-
0.173054
Texas
-
0.927661
-
0.558319
-
0.838144
Oregon
-
1.410459
-
1.901251
1.199630
In
[
10
]
:
f
=
lambda
x
:
x
.
max
(
)
-
x
.
min
(
)
In
[
11
]
:
frame
.
apply
(
f
)
Out
[
11
]
:
b
3.056583
d
2.155619
e
2.037774
dtype
:
float64
|
map()只要是作用将函数作用于一个Series的每一个元素,用法如下所示
map() 是一个Series的函数,DataFrame结构中没有map()。map()将一个自定义函数应用于Series结构中的每个元素(elements)。
In [122]: frame['e'].map(format) Out[122]: Utah 1.28 Ohio -1.55 Texas 0.20 Oregon -0.31 Name: e, dtype: object
1
2
3
4
5
6
7
8
|
In
[
122
]
:
frame
[
'e'
]
.
map
(
format
)
Out
[
122
]
:
Utah
1.28
Ohio
-
1.55
Texas
0.20
Oregon
-
0.31
Name
:
e
,
dtype
:
object
|
applymap()如果想让方程作用于DataFrame中的每一个元素,可以使用applymap().用法如下所示
In [120]: format = lambda x: '%.2f' % x In [121]: frame.applymap(format) Out[121]: b d e Utah -0.03 1.08 1.28 Ohio 0.65 0.83 -1.55 Texas 0.51 -0.88 0.20 Oregon -0.49 -0.48 -0.31
1
2
3
4
5
6
7
8
9
10
|
In
[
120
]
:
format
=
lambda
x
:
'%.2f'
%
x
In
[
121
]
:
frame
.
applymap
(
format
)
Out
[
121
]
:
b
d
e
Utah
-
0.03
1.08
1.28
Ohio
0.65
0.83
-
1.55
Texas
0.51
-
0.88
0.20
Oregon
-
0.49
-
0.48
-
0.31
|