MATLAB 的 "cellfun"的 Python 或 Numpy 方法

标签 python numpy elementwise-operations

是否有类似于 MATLAB“cellfun”的 python 或 numpy 方法?我想将一个函数应用于一个对象,该对象是一个 MATLAB 元胞数组,具有约 300k 个不同长度的元胞。

一个非常简单的例子:

>>> xx = [(4,2), (1,2,3)]
>>> yy = np.exp(xx)

Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
yy = np.exp(xx)
AttributeError: 'tuple' object has no attribute 'exp'

最佳答案

最可读/可维护的方法可能是使用 list comprehension :

yy = [ np.exp(xxi) for xxi in xx ]

这依赖于 numpy.exp 将每个元组隐式转换为 numpy.ndarray,这反过来意味着您将获得一个 numpy 列表.ndarray 返回而不是元组列表。对于几乎所有目的来说,这可能没问题,但如果你绝对必须有元组,那也很容易安排:

yy = [ tuple(np.exp(xxi)) for xxi in xx ]

出于某些目的(例如,为了避免内存瓶颈),您可能更喜欢使用 generator expression而不是列表理解(圆括号而不是方括号)。

关于MATLAB 的 "cellfun"的 Python 或 Numpy 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40007120/

相关文章:

python - 远程运行 python 脚本的更好方法

python - 峰态,条形图的偏度? - Python

python - Numpy:在 3 维中使用 np.mean

python - 如何在 numpy 中将向量乘以数组/矩阵元素?

python - 类没有属性 'tk'

python - Seaborn的sns.load_dataset()函数使用真实数据吗?

python - 检查目标时出错 : Converting FC layers to Conv2D

python - 根据来自不同数据框的两列条件乘以列?

arrays - 如何在 Perl 中按元素求和数组?

python - 具有稀疏矩阵的 numpy 元素外积