如何按块将函数应用于 pandas 数据框?

tum*_*eed 8 python python-3.x pandas

我知道apply()函数可用于将函数应用于数据框的列:

df.applymap(my_fun)
Run Code Online (Sandbox Code Playgroud)

如何按my_fun块申请?例如 1、5、10 和 20 行的块?

Max*_*axU 7

IIUC 你可以使用np.split()方法:

In [5]: df
Out[5]:
     a   b   c
0   66  64  76
1   74  15   8
2    1  29  45
3   88  98  55
4   73  24  39
5   43  86  54
6    3  10  99
7    7  36  87
8    2  26   2
9   26  49  82
10  16  38  79
11  93  78  23
12  47  35  70
13  10  47  65
14  98  81  67
15  81  13  14
16  25  47  33
17  94  48  66
18  80  52  90
19  43  40  32

In [6]: df.shape
Out[6]: (20, 3)

In [7]: [x.shape for x in np.split(df, [5, 10, 18])]
Out[7]: [(5, 3), (5, 3), (8, 3), (2, 3)]
Run Code Online (Sandbox Code Playgroud)

或者如果您需要均匀大小的块:

In [10]: [x.shape for x in np.split(df, np.arange(5, len(df), 5))]
Out[10]: [(5, 3), (5, 3), (5, 3), (5, 3)]
Run Code Online (Sandbox Code Playgroud)

使用apply()功能:

In [15]: [x.apply(np.sum) for x in np.split(df, np.arange(5, len(df), 5))]
Out[15]:
[a    302
 b    230
 c    223
 dtype: int64, a     81
 b    207
 c    324
 dtype: int64, a    264
 b    279
 c    304
 dtype: int64, a    323
 b    200
 c    235
 dtype: int64]
Run Code Online (Sandbox Code Playgroud)

pandas 如何应用函数?

Pandas 将给定的函数应用于给定的值向量:

  • 它将给定函数应用于整个列向量(逐列)如果axis=0
  • 它将给定函数应用于行向量(逐行)如果axis=1