Python 如何通过块将函数应用于数据帧?

Python 如何通过块将函数应用于数据帧?,python,python-3.x,pandas,Python,Python 3.x,Pandas,我知道该函数可用于将函数应用于数据帧的列: df.applymap(my_fun) 如何按块应用my_fun,例如1、5、10和20行的块?IIUC您可以使用以下方法: 或者,如果您需要大小均匀的块: 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)] 使用apply()函数: In [15]: [x.apply(np.sum)

我知道该函数可用于将函数应用于数据帧的列:

df.applymap(my_fun)
如何按块应用
my_fun
,例如1、5、10和20行的块?

IIUC您可以使用以下方法:

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

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)]
使用
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]
熊猫如何应用函数

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

  • 如果
    axis=0
  • 如果
    axis=1

谢谢你的帮助,Max,我不明白的是,一旦数据帧被重塑,该函数是如何应用的?@tumbleweed,我用一个小例子扩展了我的答案-请检查谢谢!,此外,熊猫如何应用该功能?。。。一个接一个?@MaxU,你能看一下吗
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]