S******n 发帖数: 90 | 1 【 以下文字转载自 Programming 讨论区 】
发信人: SeeGreen (SeeGreen), 信区: Programming
标 题: How to write a element-wise function in Python
发信站: BBS 未名空间站 (Fri Apr 5 22:17:09 2019, 美东)
大神如何编写python函数
一个大小相同矩阵中(m x n) 元素 x
倘若 x > 0 回传x
倘若 x <= 0 回传 x and 0 两者最小值, 取np.exp(x) - 1
举一个例子
a = [[-0.17985, 0.178971],[-0.15312,0.226988]]
f(a) = b
{output} b = [[-0.1646, 0.17897],[-0.14197, 0.22699]]
| i**********a 发帖数: 1402 | 2 这个应该用numpy和pandas都很容易,一行就够了。 | g*****g 发帖数: 390 | 3 练练手啊,
in bumpy (np), assume your matrix is "a" type of np.ndarray:
f = lambda x: x if x>0 else x-1
np.vectorize(f)(a)
or
np.frompyfunc(f,1,1)(a)
in pandas, assume your matrix is df, type of data frame:
df.applymap(lambda x: x if x >0 else np.exp(x)-1)
or
df.transform(lambda x: [i if i >0 else np.exp(i)-1 for i in x]) |
|