Kathiravan Natarajan
Kathiravan Natarajan

Reputation: 3498

conditional statement execution in numpy array with for loop

X = data[['x_1','x_2']].as_matrix()
y = data['y'].as_matrix()

X_pos = np.array([[X[i]  for i in range(6)if y==1]])

y is a numpy array with some values of 0 and 1.

can somebody help me with the syntax ?

  X_pos = np.array([np.array([X[i]  for i in range(8)])[y[:8].astype('bool')]])
  X_neg = np.array([[np.logical_not(y)]])

Printing X_pos,

[[[ 1.          0.87142857  0.62458472]
  [ 1.         -0.02       -0.92358804]
  [ 1.          0.36285714 -0.31893688]
  [ 1.          0.88857143 -0.87043189]]]

When I print X_neg, I am getting only

[[[ True  True  True  True False False False False]]]

Instead I should get like this ,

[[ 1.         -0.80857143  0.8372093 ]
 [ 1.          0.35714286  0.85049834]
 [ 1.         -0.75142857 -0.73089701]
 [ 1.         -0.3         0.12624585]]

Upvotes: 0

Views: 509

Answers (1)

Yasin Yousif
Yasin Yousif

Reputation: 967

assuming x and y are numpy arrays, your third line has the problem, you could rewrite it like that:

X_pos = np.array([np.array([X[i]  for i in range(6)])[y[:6].astype('bool')]])

for the fasle valuse (in y) use:

y_n = numpy.logical_not(y)
X_pos2 = np.array([np.array([X[i]  for i in range(6)])[y_n[:6]]])

here's what happen:

  • you take all the 6 elements of X

  • you apply a boolean mask of y elements for numpy array.

  • converting the whole result to numpy array (for some reason) as in your question..

Upvotes: 1

Related Questions