python取数组某几行或某几列

    科技2022-08-12  128

    逗号前是取行,逗号后是取列 取某行 X[0] #取第0行 X[0,:] #取第0行,:后面空表示该行取所有列的元素 X[0:m] #取第0至第m-1行 取某列

    X[:,0] #取第0列 X[:,-1] #取倒数第一列 ,:前面空表示该列取所有行的元素X[:,m:n] #取第m到第n-1列 例: X[:,0:1] #取第0到第1列 X[:,0:-1] #取第0到倒数第二列(-1表示倒数第一列,区间是到它的前一列)

    根据标签提取样本: 例:

    >>> X=np.array([[1,2,3,"labeled"],[5,6,7,"labeled"],[9,10,11,"labeled"],[13,14,15,"unlabeled"],[17,18,19,"unlabeled"]]) >>> X array([['1', '2', '3', 'labeled'], ['5', '6', '7', 'labeled'], ['9', '10', '11', 'labeled'], ['13', '14', '15', 'unlabeled'], ['17', '18', '19', 'unlabeled']], dtype='<U11') >>> Y=X[:,-1] >>> Y array(['labeled', 'labeled', 'labeled', 'unlabeled', 'unlabeled'], dtype='<U11') >>> index = Y != "unlabeled" >>> index array([ True, True, True, False, False]) >>> X[index] array([['1', '2', '3', 'labeled'], ['5', '6', '7', 'labeled'], ['9', '10', '11', 'labeled']], dtype='<U11') >>>
    Processed: 0.015, SQL: 8