gpt4 book ai didi

python - 如何根据列范围将 numpy 数组中的 0 值替换为其他值?

转载 作者:行者123 更新时间:2023-12-01 00:54:29 35 4
gpt4 key购买 nike

我有一个以下格式的数据集:

[[ 226 600 3.33 915.92.6 98.6 ]
[ 217 700 3.34 640. 93.7 98.5 ]
[ 213 900 3.35 662.88.8 96. ]
...
[ 108 600 2.31 291. 64. 70.4 ]
[ 125 800 3.36 1094. 65.5 84.1 ]
[109 400 2.44 941.52.3 68.7]]

每一列都是一个单独的条件,有自己的值范围。如何根据列范围将 0 值估算为大于零的值?换句话说,除了 0 之外的最差最小值。

我编写了以下代码,但它只能将0更改为列中的最小值(当然是0)或max max 因列而异。感谢您的帮助!

# Impute 0 values -- give them the worst value for that column

I, J = np.nonzero(scores == 0)
scores[I,J] = scores.min(axis=0)[J] # can only do min or max

最佳答案

一种方法是使用 masked array 查找沿列屏蔽 <=0 的最小值。并替换 0s在具有相应最小值的数组中使用 np.where :

min_gt0 = np.ma.array(r, mask=r<=0).min(0)
np.where(r == 0, min_gt0, r)
<小时/>

这是一个例子:

r = np.random.randint(0,5,(5,5))

print(r)
array([[2, 1, 3, 0, 4],
[0, 4, 4, 2, 2],
[4, 0, 0, 0, 1],
[1, 2, 2, 2, 2],
[2, 0, 4, 4, 2]])

min_gt0 = np.ma.array(r, mask=r<=0).min(0)
np.where(r == 0, min_gt0, r)

array([[2, 1, 3, 2, 4],
[1, 4, 4, 2, 2],
[4, 1, 2, 2, 1],
[1, 2, 2, 2, 2],
[2, 1, 4, 4, 2]])

关于python - 如何根据列范围将 numpy 数组中的 0 值替换为其他值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56325648/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com