为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

暮色呼如 2021-07-09 17:11:35
我正在尝试使用 for 循环将索引为 0 的所有行从一个数组获取到另一个数组中 np.concatenatei=0data0 = 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更新每个循环后,是否有更好的方法?
查看完整描述

2 回答

?
红糖糍粑

TA贡献1815条经验 获得超6个赞

你根本不需要循环:


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)

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


查看完整回答
反对 回复 2021-07-27
?
哆啦的时光机

TA贡献1779条经验 获得超6个赞

您是否只想获取所有包含 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]]


查看完整回答
反对 回复 2021-07-27
  • 2 回答
  • 0 关注
  • 314 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号