【问题标题】:Python equivalent of R apply with anonymous functionR 的 Python 等效项适用于匿名函数
【发布时间】:2014-05-05 19:01:06
【问题描述】:

在 R 中,这段代码可以正常工作:

denom <- matrix(c(0.1125588, 2.1722226, 0.5424582, 1.1727604,3.0524269 ,0.0524625 ,0.1752363 ,0.7198743,0.7282291 ,0.1646349 ,0.7574503, 2.3496857),3,4,byrow=TRUE)
indexM <- apply(denom,1,function(x) which(x==max(x)))
indexM
# 2 1 4

这是否接近 Python 等价物?它不起作用(AttributeError: 'tuple' object has no attribute 'ndim')

denom = np.array([[0.1125588, 2.1722226, 0.5424582], [1.1727604,3.0524269 ,0.0524625] ,[0.1752363 ,0.7198743,0.7282291] ,[0.1646349 ,0.7574503, 2.3496857]]);
indexM = np.apply_over_axes(lambda x,y: np.where(x == x.max(axis=1)) ,denom, axes=(0) );

【问题讨论】:

    标签: python r numpy apply


    【解决方案1】:

    您在 R 和 Python 中创建不同的数据。在 R 中创建 3 行 4 列数据,但在 Python 中创建 4 行 3 列数据。

    一旦解决了,要得到你想要的,你可以做denom.argmax(axis=1)

    denom = np.array([
       [0.1125588, 2.1722226, 0.5424582, 1.1727604],
       [3.0524269 ,0.0524625,0.1752363 ,0.7198743],
       [0.7282291,0.1646349 ,0.7574503, 2.3496857]
    ])
    
    >>> denom.argmax(axis=1)
    array([1, 0, 3], dtype=int64)
    

    (结果中的数字不同,因为 Python 使用基于 0 的索引,而 R 使用基于 1 的索引,但它们指的是相同的位置。)

    【讨论】:

    • 如果我要应用的功能是自定义功能怎么办?有没有办法传递作用于(行)向量的 lambda 函数?
    • @BrenBarn 请解释为什么 OP 的 apply_over_axes 失败。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 2015-12-03
    • 2012-09-03
    • 2018-02-20
    • 2014-05-31
    相关资源
    最近更新 更多