gpt4 book ai didi

python-3.x - 根据第二个数组的列中的值更改一个数组中的值

转载 作者:行者123 更新时间:2023-12-04 10:43:59 24 4
gpt4 key购买 nike

我有一个名为 Y_train 的一维数组包含一系列 1 和 0。我有另一个名为 sample_weight 的数组这是一个全 1 的数组,形状为 Y_train , 定义为:

sample_weight = np.ones(Y_train.shape, dtype=int)

我正在尝试更改 sample_weight 中的值到 2 ,其中对应的值在 Y_train == 0 .所以最初并排它看起来像:
Y_train        sample_weight
0 1
0 1
1 1
1 1
0 1
1 1

我希望它在转换后看起来像这样:
Y_train        sample_weight
0 2
0 2
1 1
1 1
0 2
1 1

我尝试的是使用 for循环(如下所示),但在 sample_weight 中没有一个 1 变为 2 .我想以某种方式使用 np.where()如果可能的话,函数,但这并不重要,只是想避免 for环形:
sample_weight = np.ones(Y_train.shape, dtype=int)
for num, i in enumerate(Y_train):
if i == 0:
sample_weight[num] == 2

我尝试使用所示的解决方案 here但第二个阵列没有成功。有任何想法吗???谢谢!

最佳答案

import numpy as np

Y_train = np.array([0,0,1,1,0,1])
sample_weight = np.where(Y_train == 0, 2, Y_train)

>> print(sample_weight)
[2 2 1 1 2 1]
np.where基本上就像 Excel 的“IF”一样工作:
np.where(condition, then, else)
也适用于转置数组:
Y_train = np.array([[0,0,1,1,0,1]]).T
sample_weight = np.where(Y_train == 0, 2, Y_train)

>> print(sample_weight)
[[2]
[2]
[1]
[1]
[2]
[1]]

关于python-3.x - 根据第二个数组的列中的值更改一个数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59796549/

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