Adding zeros to given positions in a numpy array - python

I have a numpy array and I want a function that takes as an input the numpy array and a list of indices and returns as an output another array which has the following property: a zero has been added to the initial array just before the position of each of the indices of the origional array.
Let me give a couple of examples:
If indices = [1] and the initial array is array([1, 1, 2]), then the output of the function should be array([1, 0, 1, 2]).
If indices = [0, 1, 3] and the initial array is array([1, 2, 3, 4]), then the output of the function should be array([0, 1, 0, 2, 3, 0, 4]).
I would like to do it in a vectorized manner without any for loops.

Had the same issue before. Found a solution using np.insert:
import numpy as np
np.insert([1, 1, 2], [1], 0)
>>> [1, 0, 1, 2]
I see #jdehesa has commented this already but adding as a permanent answer for future visitors.

Related

Python - How to remove some terms of a numpy array in specific intervals

Suppose I have the following array:
import numpy as np
x = np.array([1,2,3,4,5,
1,2,3,4,5,
1,2,3,4,5])
How can I manipulate it to remove the term in equally spaced intervals and adapt the new length for it? For example, I'd like to have:
x = [1,2,3,4,
1,2,3,4,
1,2,3,4]
Where the terms from positions 4, 9, and 14 were excluded (so every 5 terms, one gets excluded). If possible, I'd like to have a code that I could use for an array with length N. Thank you in advance!
In your case, you can simply run code below after initializing the x array(as you did your question):
x.reshape(3,5)[:,:4]
Output
array([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]])
If you are interested in getting a vector and not a matrix(such as the output above), you can call the flatten function on the code above:
x.reshape(3,5)[:,:4].flatten()
Output
array([1, 2, 3, 4,
1, 2, 3, 4,
1, 2, 3, 4])
Explanation
Since x is a numpy array, we can use NumPy in-built functions such as reshape. This function, which has a self-explanatory name, shapes the array into the desired format. x was a vector of 15 elements. Therefore, running x.reshape(3,5) gives us a matrix with 3 rows and five columns. [:, :4] is to reselect the first four columns. flatten function changes a matrix into a vector.
IIUC, you can use a boolean mask generated with the modulo (%) operator:
N = 5
mask = np.arange(len(x))%N != N-1
x[mask]
output: array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
This works even if your array has not a size that is a multiple of N

How to find the index of all minimum elements in a numpy array in python?

Suppose I have a numpy array
a = np.array([0,2,3,4,5,1,9,0,0,7,9,0,0,0]).reshape(7,2)
I want to find out the indices of all the times the minimum element (here 0) occurs in the 2nd column. Using argmin I can find out the index of when 0 is occurring for the first time. How can I do this in Python?
Using np.flatnonzero on a[:, 1]==np.min(a) is the most starightforward way:
In [3]: idxs = np.flatnonzero(a[:, 1]==np.min(a))
In [4]: idxs
Out[4]: array([3, 5, 6])
After you reshaped your array it looks like this:
array([[0, 2],
[3, 4],
[5, 1],
[9, 0],
[0, 7],
[9, 0],
[0, 0]])
You can get all elements that are of the same value by using np.where. IN your case the following would work:
np.where(a.T[-1] == a.argmin())
# This would give you (array([3, 5, 6]),)
What happens here is that you create a transposed view on the array. This means you can easily access the columns. The term view here means that the a array itself is not changed for that. This leaves you with:
a.T
array([[0, 3, 5, 9, 0, 9, 0],
[2, 4, 1, 0, 7, 0, 0]])
From this you select the last line (i.e. the last column of a) by using the index -1. Now you have the array
array([2, 4, 1, 0, 7, 0, 0])
on which you can call np.where(condititon), which gives you all indices for which the condition is true. In your case the condition is
a.T[-1] == a.argmin()
which gives you all entries in the selected line of the transposed array that have the same value as np.argmin(a) which, as you said, is 0 in your case.

Slice an array starting from first nonzero element

I have an array with leading zeros, and I want the array from the first nonzero element.
For example, I have an array
x=[0,0,0,0,0,3,2,0,0,4,5]
I want to obtain :
x=[3,2,0,0,4,5]
What you have is a list, not an array. This is a pure-Python solution, though you might consider converting your list into a NumPy array and going with the Divakar's solution for better performance (if and only if you plan on using NumPy for downstream processing)
In [1]: from itertools import dropwhile
In [2]: from operator import not_
In [3]: x = [0,0,0,0,0,3,2,0,0,4,5]
In [4]: list(dropwhile(not_, x))
Out[4]: [3, 2, 0, 0, 4, 5]
Use np.argmax on non-zeros to get the starting non-zero index and then simply slice it -
x[(x!=0).argmax():]
Sample run -
In [71]: x
Out[71]: array([0, 0, 0, 0, 0, 3, 2, 0, 0, 4, 5])
In [72]: x[(x!=0).argmax():]
Out[72]: array([3, 2, 0, 0, 4, 5])

Python reshape list to ndim array

Hi I have a list flat which is length 2800, it contains 100 results for each of 28 variables: Below is an example of 4 results for 2 variables
[0,
0,
1,
1,
2,
2,
3,
3]
I would like to reshape the list to an array (2,4) so that the results for each variable are in a single element.
[[0,1,2,3],
[0,1,2,3]]
You can think of reshaping that the new shape is filled row by row (last dimension varies fastest) from the flattened original list/array.
If you want to fill an array by column instead, an easy solution is to shape the list into an array with reversed dimensions and then transpose it:
x = np.reshape(list_data, (100, 28)).T
Above snippet results in a 28x100 array, filled column-wise.
To illustrate, here are the two options of shaping a list into a 2x4 array:
np.reshape([0, 0, 1, 1, 2, 2, 3, 3], (4, 2)).T
# array([[0, 1, 2, 3],
# [0, 1, 2, 3]])
np.reshape([0, 0, 1, 1, 2, 2, 3, 3], (2, 4))
# array([[0, 0, 1, 1],
# [2, 2, 3, 3]])
You can specify the interpretation order of the axes using the order parameter:
np.reshape(arr, (2, -1), order='F')
Step by step:
# import numpy library
import numpy as np
# create list
my_list = [0,0,1,1,2,2,3,3]
# convert list to numpy array
np_array=np.asarray(my_list)
# reshape array into 4 rows x 2 columns, and transpose the result
reshaped_array = np_array.reshape(4, 2).T
#check the result
reshaped_array
array([[0, 1, 2, 3],
[0, 1, 2, 3]])
The answers above are good. Adding a case that I used.
Just if you don't want to use numpy and keep it as list without changing the contents.
You can run a small loop and change the dimension from 1xN to Nx1.
tmp=[]
for b in bus:
tmp.append([b])
bus=tmp
It maybe not efficient in case of very large numbers. But it works for small set of numbers.
Thanks

How to construct a ndarray from a numpy array? python

I can't seem to convert it into an ndarray in numpy, i've read http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html but it didn't show me how i can convert my input data as shown below into an ndarray.
How to construct a ndarray from a numpy array or a list of integer lists?
*What's the difference between ndarray and array?* I could just use an array type right?
I have a list of integer counts like this
[[1, 2, 4, 1, 5],
[6, 0, 0, 0, 2],
[0, 0, 0, 1, 0]]
And i manage to use this code to create a np.array as shown in http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html#numpy.array
import numpy as np
x = [[1, 2, 4, 1, 5],
[6, 0, 0, 0, 2],
[0, 0, 0, 1, 0]]
print np.array(x)
[out]:
[[1 2 4 1 5]
[6 0 0 0 2]
[0 0 0 1 0]]
But I can't change it into a np.ndarray with this code:
import numpy as np
x = [[1, 2, 4, 1, 5],
[6, 0, 0, 0, 2],
[0, 0, 0, 1, 0]]
print np.ndarray(x)
I got an error:
Traceback (most recent call last):
File "/home/alvas/workspace/sklearntut/test.py", line 7, in <module>
print np.ndarray(x)
TypeError: an integer is required
How do I create a np.ndarray with the list of integer counts i've got? What integer is the TypeError talking about?
An ndarray is a NumPy array.
>>> x = np.array([1, 2, 3])
>>> type(x)
<type 'numpy.ndarray'>
The difference between np.ndarray and np.array is that the former is the actual type, while the latter is a flexible shorthand function for constructing arrays from data in other formats. The TypeError comes your use of np.array arguments to np.ndarray, which takes completely different arguments (see docstrings).
Though the accepted response is correct, that didn't help me actually create a 1-dimensional array of arrays.
As this thread is the first answer at Google, I post my work around, even if it isn't elegant solution (please don't hesitate to point one out to me):
import numpy as np
# Create example array
initial_array = np.ones(shape = (2,2))
# Create array of arrays
array_of_arrays = np.ndarray(shape = (1,), dtype = "object")
array_of_arrays[0] = initial_array
Be aware that array_of_arrays is in this case mutable, i.e. changing initial_array automatically changes array_of_arrays .
I will combine the accepted solution with the fixed code.
As said in the accepted solution, an ndarray is a NumPy array.
This essentially means that you should use np.array when constructing an ndarray from a list of lists, a list of tuples, a tuple of lists...
Fixed code fragment:
import numpy as np
x = [[1, 2, 4, 1, 5],
[6, 0, 0, 0, 2],
[0, 0, 0, 1, 0]]
# The difference: we call np.array
print np.array(x)
Hope this will help others out as this is the first Google answer.

Categories

Resources