猿问

我正在尝试使用 for 循环和 np.concatenate 将索引为 0

我正在尝试使用 for 循环将索引为 0 的所有行从一个数组获取到另一个数组中 np.concatenate


i=0

data0 = np.zeros((1,257))

data0.shape = (257,)

for j in range (0,7291):

    if datatrain[j,i] == 0:

       data0 = np.concatenate((data0, datatrain[j,:]))

我的问题是,在data0更新每个循环后,是否有更好的方法?


暮色呼如
浏览 315回答 2
2回答

红糖糍粑

你根本不需要循环:col = 0indices = np.where(datatrain[:, col] == 0)[0]zero_col = np.zeros_like(indices).reshape(-1, 1)data_of_interest = np.concatenate((zero_col, datatrain[indices, :]), axis=1)由于我没有您的数据集样本,因此无法针对您的特定情况对其进行测试。

哆啦的时光机

您是否只想获取所有包含 0 的行?你可以这样做:import numpy as npdatatrain = np.arange(25).reshape(5, 5)datatrain[0][1] # 1st row has two 0s (arange starts at 0)datatrain[1][2] = 0 # 2nd row now has a 0datatrain[-1][4] = 0 # last row now has a 0print(datatrain)# Outputs:# [[ 0  0  2  3  4]# [ 5  6  0  8  9]# [10 11 12 13 14]# [15 16 17 18 19]# [20 21 22 23  0]]rows_inds_with_zeros, cols_with_zeros = np.where(datatrain == 0)print(rows_inds_with_zeros)# Ouputs: [0 0 1 4] (as expected, note 0th row included twice)# You probably don't want the row twice if it has two 0s,# although that's what your code does, hence np.uniquerows_with_zeros = datatrain[np.unique(rows_inds_with_zeros)]print(rows_with_zeros) # Or call it data0, whatever you like# Outputs:# [[ 0  0  2  3  4]# [ 5  6  0  8  9]# [20 21 22 23  0]]
随时随地看视频慕课网APP

相关分类

Python
我要回答