【问题标题】:When I try to replace a portion of a numpy array, nothing happens当我尝试替换 numpy 数组的一部分时,没有任何反应
【发布时间】:2021-03-18 16:38:33
【问题描述】:

我有以下代码

currSub 是一个长度为 2850 的 Dataframe,我提取了时间戳(数字 1 到 2850)和一个相同长度的概率向量。

我的目标是将向量 currProb 放在向量 realign 中,从位置 50 开始,其他零保持不变。

当我运行最后两行中的任何一行时,什么都没有发生。有人可以解释为什么这些值不会改变吗?

alignPoint = 50
x = np.arange(0,3000)

subTimes = np.arange(2850)/2
subProb = np.ones(2850)-0.5
        
realign = np.zeros_like(x)
sTRe = np.arange(alignPoint,alignPoint+len(subTimes)).astype(int)

realign[alignPoint:alignPoint+len(subTimes)] = subProb
np.put(realign,sTRe,subProb)

【问题讨论】:

  • 您有subProb,但没有currSubcurrProb

标签: python arrays numpy indexing


【解决方案1】:

realign 具有数据类型 int64。当您为其分配浮点值时,它们会转换为整数类型,这意味着它们会向下舍入。

由于subProb 包含 0.5,您将现有的 0 值替换为新的 0 值。

为避免这种情况,请使用与 subProb 相同的 dtype 创建 realign

realign = np.zeros_like(x, dtype=subProb.dtype)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多