python - 将带有参数的函数应用于数据帧
问题描述
我正在尝试将函数应用于数据框,其中参数来自数据框本身。有没有办法简洁地做到这一点?
df:
| a | b | c | d |
A | 20 | 15 | 33 | 5 |
B | 5 | 6 | 10 | 8 |
C | 10 | 15 | 5 | 10|
应用于每个单元格的函数
# c = sum of the current column
# r = sum of the current row
# t = sum of all values
def calcIndex(x, c, r, t):
return (x/c)*(t/r)*100
结果
| a | b | c | d |
A | 111 | 81 | 134 | 42 |
B | 70 | 82 | 102 | 170 |
C | 101 | 148 | 37 | 154 |
我已经尝试df.apply
但不确定如何访问特定的行/列总数,具体取决于x
正在计算的
解决方案
此处的问题DataFrame.apply
可能是按列或按索引循环,而不是按两者循环,因此如果在一个函数中需要两者,则不能在此处使用。
更好更快的是在输出中使用带有和的矢量化函数DataFrame.div
,最后使用with表示整数:DataFrame.mul
DataFrame.sum
DataFrame.round
DataFrame.astype
c = df.sum(axis=1)
r = df.sum()
t = r.sum()
df1 = df.div(c, axis=0).mul(t).div(r).mul(100).round().astype(int)
print (df1)
a b c d
A 111 81 134 42
B 70 82 102 170
C 101 148 37 154
为了提高性能,可以使用numpy
:
#pandas 0.24+
arr = df.to_numpy()
#pandas below
#arr = df.values
c = arr.sum(axis=1)
r = arr.sum(axis=0)
t = r.sum()
out = np.round(arr / c[:, None] * t / r * 100).astype(int)
df = pd.DataFrame(out, index=df.index, columns=df.columns)
print (df)
a b c d
A 111 81 134 42
B 70 82 102 170
C 101 148 37 154
推荐阅读
- git - jenkins maven 不推送我的 pom 并使用旧的 maven-release-prepare 版本
- json - 如何将json对象与角度中相同元素的分组绑定
- javascript - 如何将数据从 Node 发送到另一台服务器
- powershell - 使用 powershell 在多台机器上远程运行安装文件 (.exe)
- json - 如何使用 volley 库在 android 中发出 JSONObject 的请求(类型:POST)?
- codeigniter-3 - 在 Codeigniter 中的 php 7.2 中出现错误“未定义的函数 mcrypt_create_iv()”
- javascript - 链接即使打开也没有激活
- python - 如何在清除子集总和时修复此错误?
- ios - AVPlayer/AVFoundation 播放指定 HLS 带宽和分辨率
- debugging - 如何在 sonarqube 中查找错误/漏洞的初始数量