简体   繁体   English

1 在由另一个 numpy 数组给出的特定列索引处的全零 numpy 数组的每一行中

[英]1 in each row of an all zeros numpy array at particular column index given by another numpy array

I have an array of some given size eg 4x4 with all zeros,我有一个给定大小的数组,例如全为零的 4x4,

a = np.zeros((4,4))

and I want to put 1 in each row at the column index given by another array我想在另一个数组给出的列索引处的每一行中放置 1

b = np.array([0,1,2,1])

so the resulted array should look like this,所以结果数组应该是这样的,

a = 
1   0   0   0
0   1   0   0
0   0   1   0
0   1   0   0

How can I do this for a large array of size (mxn) given b of size (mx1) .对于给定 b 的大小(mx1)的大数组(mxn) ,我该如何做到这一点。

Thank You and Best Regards,感谢你并致以真诚的问候,

You can use this simple way of indexing 2D array:您可以使用这种简单的方法来索引二维数组:

>>> a[np.arange(len(a)), b] = 1
>>> a
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 1., 0., 0.]])

Loop through rows in a and values in b using zip() :使用zip()遍历 a 中的行和ba值:

for row, idx in zip(a, b):
    row[idx] = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 制作一个 numpy 零数组,其中每行有 8 个零,对应于输出的索引更改为 1 - Make an numpy array of zeros, where each row has 8 zeros, and the index which corresponds to the output changes to 1 索引 numpy 数组,每列有两个数组的开始和结束 - Index numpy array with two arrays given start and end for each column 用零填充一个numpy数组,并使用另一个数组作为一个索引 - Padding a numpy array with zeros, and using another array as an index for ones 如何用给定索引范围/切片的零填充 numpy 数组 - How to fill numpy array of zeros with ones given index ranges/slices 修改 NumPy 数组的特定行/列 - Modify a particular row/column of a NumPy array 将零添加到numpy数组中的给定位置 - Adding zeros to given positions in a numpy array 将 numpy 数组的每一行转换为 numpy 数组 - Transform each row of a numpy array into a numpy array numpy 2d数组,将每行的每个索引剪切到该索引和特定列的最小值 - Numpy 2d array, clipping each index of each row to the minimum of that index and a specific column 基于特定列的值对 numpy 矩阵进行分组,仅在给定数组的行索引上 - Group numpy matrix based on value of particular column, only on row indices from given array numpy:用numpy数组替换numpy数组中的零 - Numpy: replacing zeros in numpy array with a numpy array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM