【问题标题】:I'm trying to get all rows with an Index 0 from one array into another one with for loop and np.concatenate我正在尝试使用 for 循环和 np.concatenate 从一个数组中获取索引为 0 的所有行到另一个数组中
【发布时间】:2019-03-26 22:56:21
【问题描述】:

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

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 之后,是否有更好的方法来解决这个问题?

【问题讨论】:

  • 首选的迭代方式是在列表中累积行,并且只构建一次数组。

标签: python pandas numpy numpy-ndarray


【解决方案1】:

你根本不需要循环:

col = 0
indices = 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)

由于我没有您的数据集样本,因此无法针对您的具体情况对其进行测试。

【讨论】:

    【解决方案2】:

    您想只获取所有包含 0 的行吗?你可以这样做:

    import numpy as np
    datatrain = 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 0
    datatrain[-1][4] = 0 # last row now has a 0
    print(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.unique
    rows_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]]
    

    HTH。

    【讨论】:

      猜你喜欢
      • 2018-05-09
      • 2021-06-24
      • 2022-01-15
      • 2021-12-29
      • 2021-11-24
      • 1970-01-01
      • 2018-12-08
      • 2018-03-28
      • 1970-01-01
      相关资源
      最近更新 更多