简体   繁体   中英

Split 2D numpy array with condition

I want to split a 2D array based on the value in row 13. Input is a 2D Numpy array, but I cant figure out how to create Arrays as an output, as np.append gives me tupels. (So I can for example not use np.median on it)

import numpy as np

D = np.load('train_data.npy')

E = []
F = []

for i, item in enumerate(D):
    if D[i][13]==0:
        np.append(E,item)
    else:
        np.append(F,item)

threshold=np.median(E[:, 7])
#Throws error, because E is a now tuple. It works on D.

Vectorized version of the code above.

import numpy as np
E = D[np.isclose(D[:,13], 0)].ravel().tolist()
F = D[~np.isclose(D[:,13], 0)].ravel().tolist()

It is better to use almost equal comparison when working with floating point numbers, because in some cases (due to errors of number representation in memory), eg 1.0e-20 may be treated non-equal to zero.

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