大Pandasmap、applymap和应用方法的差异

2024-04-19 15:23:12 发布

您现在位置:Python中文网/ 问答频道 /正文

你能告诉我什么时候用这些矢量化方法来处理基本的例子吗?

我看到map是一个Series方法,而其余的是DataFrame方法。但是我对applyapplymap方法感到困惑。为什么我们有两种方法将函数应用于数据帧?同样,简单的例子说明了使用将是太好了!


Tags: 数据方法函数mapdataframe矢量化例子series
2条回答

直接摘自韦斯·麦金尼的Python for Data Analysis书,第132页(我强烈推荐这本书):

Another frequent operation is applying a function on 1D arrays to each column or row. DataFrame’s apply method does exactly this:

In [116]: frame = DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['Utah', 'Ohio', 'Texas', 'Oregon'])

In [117]: frame
Out[117]: 
               b         d         e
Utah   -0.029638  1.081563  1.280300
Ohio    0.647747  0.831136 -1.549481
Texas   0.513416 -0.884417  0.195343
Oregon -0.485454 -0.477388 -0.309548

In [118]: f = lambda x: x.max() - x.min()

In [119]: frame.apply(f)
Out[119]: 
b    1.133201
d    1.965980
e    2.829781
dtype: float64

Many of the most common array statistics (like sum and mean) are DataFrame methods, so using apply is not necessary.

Element-wise Python functions can be used, too. Suppose you wanted to compute a formatted string from each floating point value in frame. You can do this with 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

The reason for the name applymap is that Series has a map method for applying an element-wise function:

In [122]: frame['e'].map(format)
Out[122]: 
Utah       1.28
Ohio      -1.55
Texas      0.20
Oregon    -0.31
Name: e, dtype: object

总之,apply在数据帧的行/列基础上工作,applymap在数据帧上按元素工作,map在序列上按元素工作。

除了其他答案,在a Series中还有mapapply

Apply可以从序列中生成数据帧;但是,map只会在另一个序列的每个单元格中放置一个序列,这可能不是您想要的。

In [40]: p=pd.Series([1,2,3])
In [41]: p
Out[31]:
0    1
1    2
2    3
dtype: int64

In [42]: p.apply(lambda x: pd.Series([x, x]))
Out[42]: 
   0  1
0  1  1
1  2  2
2  3  3

In [43]: p.map(lambda x: pd.Series([x, x]))
Out[43]: 
0    0    1
1    1
dtype: int64
1    0    2
1    2
dtype: int64
2    0    3
1    3
dtype: int64
dtype: object

另外,如果我有一个带有副作用的函数,比如“连接到web服务器”,我可能会使用apply,只是为了清楚起见。

series.apply(download_file_for_every_element) 

Map不仅可以使用函数,还可以使用字典或其他系列。假设您要操作permutations

采取

1 2 3 4 5
2 1 4 5 3

这个排列的平方是

1 2 3 4 5
1 2 5 3 4

你可以用map来计算。不确定是否记录了self-application,但它可以在0.15.1中工作。

In [39]: p=pd.Series([1,0,3,4,2])

In [40]: p.map(p)
Out[40]: 
0    0
1    1
2    4
3    2
4    3
dtype: int64

相关问题 更多 >