简体   繁体   中英

How to I extract the 2nd element in this numpy array, where the 2nd element of each row is another numpy array

Here is the sample numpy array

new2 = np.array([[0, np.array([ 4928722,  3922609, 14413953, 10103423,  8948498])],
       [1,
        np.array([12557217,  5572869, 13415223,  2532000, 14609022,  9830632,
        9800679,  7504595, 10752682])],
       [2,
        np.array([10458710,  7176517, 10268240,  4173086,  8617671,  4674075,
       12580461,  2434641,  3694004,  9734870,  1314108,  8879955,
        6597761,  7034485,  3008940,  9816877,  1748801, 10159466,
        2745090, 14842579,   788308,  5984365])],
       [62711, np.array([ 6159359,  5003282, 11818909, 11760670])],
       [62712,
        np.array([ 4363069,  8566447,  9547966, 14554871,  2108131, 12207856,
       14840255, 13087558])],
       [62713,
        np.array([11252023,  8710787,  4233645, 11415316, 13888594,  7410770,
       13672430,  6677251, 10431890,  3447966, 12675925,   729773])]] )

I want to extract only the 2nd element in each row; the varying length numpy arrays. I want these vary length numpy arrays to be in it's own numpy array.

I tried doing this

new2[:][1]

Which usually would mean that to contain all row indexes, and column index of 1. But for some reason it results exactly the same as new2[1]. The result is

array([1,
       array([12557217,  5572869, 13415223,  2532000, 14609022,  9830632,
        9800679,  7504595, 10752682])], dtype=object)

Only one row, which contains both the int and the numpy array.

new2[:] selects the entire array which is why new[:][1] selects the second row. arr[X,Y] and arr[X][Y] only yield the same result if X is a number. As far as I can tell, the only legit reason for using arr[X][Y] is if you want to support arrays and nested lists etc. with the same code. Failing that arr[X,Y] should always be preferred. So use new2[:,1] .

Why not just:

for x in new2:
    print(x[1][1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM