0

I have a database with the following array:

array = np.array([[1,4,1,1,0,0],[4,5,6,3,0,0],[1,4,5,6,0,0]])

I'm working with the datas in column, for example:

array[:,2]

out: array([1, 6, 5])

I would like to create a new array without the columns of 0

To do that, I created an array of zeros:

array_zero = np.zeros((3,6))

Then, I compare each index with this array:

index = 0
while (array[:,index] != array_zero[:,0]):
    index = index + 1

When I have the index of the first column of 0, I know that the following columns will be columns of 0.

So, I would want to create my new array like this:

array_new = np.array(3,index + 1)

for i in range(index+ 1):
    array_new[:,i] = array[:,i]

In the while loop, I have the following error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I tried the following:

while ((array[:,index] != array_zero[:,0]).all):
    index = index + 1

or

while ((array[:,index] != array_zero[:,0]).any):
    index = index + 1

And I have the following error:

IndexError: index 6 is out of bounds for axis 1 with size 6

Here is the code:

import numpy as np

index = 0

array = np.array([[1,4,1,1,0,0],[4,5,6,3,0,0],[1,4,5,6,0,0]])

array_zero = np.zeros((3,6))


while (array[:,index] != array_zero[:,0]):
    index = index + 1

array_new = np.array(3,index + 1)

for i in range(index+ 1):
    array_new[:,i] = array[:,i]

Thank you for your help

1
  • 1
    Comparing arrays in Numpy compares each element pair and returns an array of the comparison results. The boolean truth value of such an array is ambiguous. You might want to use np.any(array) instead. That tells you whether any of the values is true (!= 0). Commented Jul 25, 2018 at 13:48

2 Answers 2

4

You might want to us Numpy's internal functions more:

a = np.array([[1,4,1,1,0,0],[4,5,6,3,0,0],[1,4,5,6,0,0]])
a

array([[1, 4, 1, 1, 0, 0],
       [4, 5, 6, 3, 0, 0],
       [1, 4, 5, 6, 0, 0]])

Then:

a[:,np.any(a, axis=0)]

array([[1, 4, 1, 1],
       [4, 5, 6, 3],
       [1, 4, 5, 6]])
Sign up to request clarification or add additional context in comments.

Comments

2

This can be solved with numpy:

In[0]: array = np.array([[1,4,1,1,0,0],[4,5,6,3,0,0],[1,4,5,6,0,0]])
In[1]: array[:,~(array==0).all(0)]
Out[1]: 
array([[1, 4, 1, 1],
       [4, 5, 6, 3],
       [1, 4, 5, 6]])

Essentially you are finding columns that sum up to 0, and then slice them out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.