gpt4 book ai didi

python - 如何按 block 将函数应用于 Pandas 数据框?

转载 作者:太空宇宙 更新时间:2023-11-03 10:55:38 26 4
gpt4 key购买 nike

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

df.applymap(my_fun)

如何按 block 应用 my_fun?例如 1、5、10 和 20 行的 block ?

最佳答案

您可以使用 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)]

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

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]

How does pandas apply a function?

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

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

关于python - 如何按 block 将函数应用于 Pandas 数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41447177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com