This supposedly simple task is driving me a bit mad.
Say you want to create an array by concatenating an integer to another array:
import numpy as np
a = 4
b = np.array([1, 10, 24, 12])
A = np.array(a, b)
gives me TypeError: data type not understood. Which I understand because I'm mixing an integer with a list. Now if I do A = np.array([a], b) I get the same result, if I get A = np.array([a] + b) I don't get the expected result.
Also, I tried A = np.array([a, *b]) with SyntaxError: can use starred expression only as assignment target.
How's the proper way to do this?
What's wrong with using np.append?:
In [20]:
a = 4
b = np.array([1, 10, 24, 12])
np.append(a,b)
Out[20]:
array([ 4, 1, 10, 24, 12])
You can use the concatenate function to do this
A = np.concatenate(([a], b))
For your case, I think using append is "better" since it is less error prone as it accepts scalars as well, (as my own mistake clearly shows!) and (arguably) slightly more readable.
You can also use hstack (http://docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html):
In [194]: a = 4
In [195]: b = np.array([1, 10, 24, 12])
In [196]: np.hstack((a,b))
Out[196]: array([ 4, 1, 10, 24, 12])
hstack has the advantage that it can concatenate as many arrays/lists as you want (e.g. np.hstack((a, b, a, b, [0, 2, 4, 6, 8])))
Related
I'm converting some Matlab code into Python, and I've found a line I can not understand:
Y = reshape(X(j+(1:a*b),:),[b,a,p])
I know that the reshape function has a numpy analog and I have read the Matrix Indexing in MATLAB document, but I can't seem to comprehend that line enough to convert it to numpy indexing/slicing.
I tried the online converter OMPC but it uses functions that are not defined outside of it (like mslice):
Y = reshape(X(j + (mslice[1:a * b]), mslice[:]), mcat([b, a, p]))
I've also tried the SMOP converter but the result is also hard to understand:
Y = reshape(X(j + (arange(1, dot(a, b))), arange()), concat([b, a, p]))
Could you explain the conversion in simple Matlab to numpy indexing/slicing rules?
Y = X[j+np.arange(a*b),:].reshape((b,a,p))
Without knowing what you exactly want, this is a translation of the matlab line to python.
Notice that matlab indexes start at 1, while numpy's start at 0. So depending on the other lines the inner line could be either np.arange(a*b) or np.arange(1,a*b).
Also you don't really need to use the second index of X, so X[1,:]==X[1] is True
In an Octave session:
>> 1:3*3
ans =
1 2 3 4 5 6 7 8 9
In numpy ipython:
In [8]: np.arange(1,10)
Out[8]: array([1, 2, 3, 4, 5, 6, 7, 8, 9])
In [9]: np.arange(3*3)
Out[9]: array([0, 1, 2, 3, 4, 5, 6, 7, 8])
I have an array:
a = [1, 3, 5, 7, 29 ... 5030, 6000]
This array gets created from a previous process, and the length of the array could be different (it is depending on user input).
I also have an array:
b = [3, 15, 67, 78, 138]
(Which could also be completely different)
I want to use the array b to slice the array a into multiple arrays.
More specifically, I want the result arrays to be:
array1 = a[:3]
array2 = a[3:15]
...
arrayn = a[138:]
Where n = len(b).
My first thought was to create a 2D array slices with dimension (len(b), something). However we don't know this something beforehand so I assigned it the value len(a) as that is the maximum amount of numbers that it could contain.
I have this code:
slices = np.zeros((len(b), len(a)))
for i in range(1, len(b)):
slices[i] = a[b[i-1]:b[i]]
But I get this error:
ValueError: could not broadcast input array from shape (518) into shape (2253412)
You can use numpy.split:
np.split(a, b)
Example:
np.split(np.arange(10), [3,5])
# [array([0, 1, 2]), array([3, 4]), array([5, 6, 7, 8, 9])]
b.insert(0,0)
result = []
for i in range(1,len(b)):
sub_list = a[b[i-1]:b[i]]
result.append(sub_list)
result.append(a[b[-1]:])
You are getting the error because you are attempting to create a ragged array. This is not allowed in numpy.
An improvement on #Bohdan's answer:
from itertools import zip_longest
result = [a[start:end] for start, end in zip_longest(np.r_[0, b], b)]
The trick here is that zip_longest makes the final slice go from b[-1] to None, which is equivalent to a[b[-1]:], removing the need for special processing of the last element.
Please do not select this. This is just a thing I added for fun. The "correct" answer is #Psidom's answer.
I'm new to python and I am stuck. I've been playing with this a lot. I am trying to get my 3 lists to join and when I do python says that the new list only contains 1 item. How do I get them to merge completely?
here is the code I have now :
(where avg[] is some array containing lots of data)
q=avg[0:40]
p=avg[53:70]
u=avg[95:145]
pu=p+u
NF=[numpy.append(q,pu)]
>>>len(NF)
>>1
but the actual length of all the items is 107.
Please help
If avg is list, then q, p and u are slices of a list and therefore will be lists too. In that case, you could concatenate the lists using addition:
q+p+u
If you want a NumPy array, you could use np.concatenate:
In [48]: avg = np.arange(20)
In [49]: q = avg[0:4]
In [50]: p = avg[5:7]
In [51]: u = avg[9:14]
In [52]: np.concatenate([q,p,u])
Out[52]: array([ 0, 1, 2, 3, 5, 6, 9, 10, 11, 12, 13])
I made the arrays smaller so the result is easier to check.
Other alternatives include np.hstack and np.r_:
In [53]: np.hstack([q,p,u])
Out[53]: array([ 0, 1, 2, 3, 5, 6, 9, 10, 11, 12, 13])
In [54]: np.r_[q,p,u]
Out[54]: array([ 0, 1, 2, 3, 5, 6, 9, 10, 11, 12, 13])
In the above examples, q, p, and u may be NumPy arrays or Python lists. In each case a NumPy array is returned.
You put your array in another array. try this:
NF=numpy.append(q,pu)
q=avg[0:40]
p=avg[53:70]
u=avg[95:145]
pu=p+u
NF=[numpy.append(q,pu)] #problem right here just do NF = numpy.append(q,pu)
>>>len(NF)
>>1
Okay this is going to be horrifically slow, maybe numpy has its own way of doing it, but using python way and provided that you have one-dimensional arrays, try this:
from itertools import chain
items = chain.from_iterable([avg[0:40], avg[53:70], avg[95:145]])
The statements about will return a generator, that can be converted into a list that reports you its length.
item_list = [x for x in items]
len(item_list)
What is the most efficient way to remove the last element from a numpy 1 dimensional array? (like pop for list)
NumPy arrays have a fixed size, so you cannot remove an element in-place. For example using del doesn't work:
>>> import numpy as np
>>> arr = np.arange(5)
>>> del arr[-1]
ValueError: cannot delete array elements
Note that the index -1 represents the last element. That's because negative indices in Python (and NumPy) are counted from the end, so -1 is the last, -2 is the one before last and -len is actually the first element. That's just for your information in case you didn't know.
Python lists are variable sized so it's easy to add or remove elements.
So if you want to remove an element you need to create a new array or view.
Creating a new view
You can create a new view containing all elements except the last one using the slice notation:
>>> arr = np.arange(5)
>>> arr
array([0, 1, 2, 3, 4])
>>> arr[:-1] # all but the last element
array([0, 1, 2, 3])
>>> arr[:-2] # all but the last two elements
array([0, 1, 2])
>>> arr[1:] # all but the first element
array([1, 2, 3, 4])
>>> arr[1:-1] # all but the first and last element
array([1, 2, 3])
However a view shares the data with the original array, so if one is modified so is the other:
>>> sub = arr[:-1]
>>> sub
array([0, 1, 2, 3])
>>> sub[0] = 100
>>> sub
array([100, 1, 2, 3])
>>> arr
array([100, 1, 2, 3, 4])
Creating a new array
1. Copy the view
If you don't like this memory sharing you have to create a new array, in this case it's probably simplest to create a view and then copy (for example using the copy() method of arrays) it:
>>> arr = np.arange(5)
>>> arr
array([0, 1, 2, 3, 4])
>>> sub_arr = arr[:-1].copy()
>>> sub_arr
array([0, 1, 2, 3])
>>> sub_arr[0] = 100
>>> sub_arr
array([100, 1, 2, 3])
>>> arr
array([0, 1, 2, 3, 4])
2. Using integer array indexing [docs]
However, you can also use integer array indexing to remove the last element and get a new array. This integer array indexing will always (not 100% sure there) create a copy and not a view:
>>> arr = np.arange(5)
>>> arr
array([0, 1, 2, 3, 4])
>>> indices_to_keep = [0, 1, 2, 3]
>>> sub_arr = arr[indices_to_keep]
>>> sub_arr
array([0, 1, 2, 3])
>>> sub_arr[0] = 100
>>> sub_arr
array([100, 1, 2, 3])
>>> arr
array([0, 1, 2, 3, 4])
This integer array indexing can be useful to remove arbitrary elements from an array (which can be tricky or impossible when you want a view):
>>> arr = np.arange(5, 10)
>>> arr
array([5, 6, 7, 8, 9])
>>> arr[[0, 1, 3, 4]] # keep first, second, fourth and fifth element
array([5, 6, 8, 9])
If you want a generalized function that removes the last element using integer array indexing:
def remove_last_element(arr):
return arr[np.arange(arr.size - 1)]
3. Using boolean array indexing [docs]
There is also boolean indexing that could be used, for example:
>>> arr = np.arange(5, 10)
>>> arr
array([5, 6, 7, 8, 9])
>>> keep = [True, True, True, True, False]
>>> arr[keep]
array([5, 6, 7, 8])
This also creates a copy! And a generalized approach could look like this:
def remove_last_element(arr):
if not arr.size:
raise IndexError('cannot remove last element of empty array')
keep = np.ones(arr.shape, dtype=bool)
keep[-1] = False
return arr[keep]
If you would like more information on NumPys indexing the documentation on "Indexing" is quite good and covers a lot of cases.
4. Using np.delete()
Normally I wouldn't recommend the NumPy functions that "seem" like they are modifying the array in-place (like np.append and np.insert) but do return copies because these are generally needlessly slow and misleading. You should avoid them whenever possible, that's why it's the last point in my answer. However in this case it's actually a perfect fit so I have to mention it:
>>> arr = np.arange(10, 20)
>>> arr
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
>>> np.delete(arr, -1)
array([10, 11, 12, 13, 14, 15, 16, 17, 18])
5.) Using np.resize()
NumPy has another method that sounds like it does an in-place operation but it really returns a new array:
>>> arr = np.arange(5)
>>> arr
array([0, 1, 2, 3, 4])
>>> np.resize(arr, arr.size - 1)
array([0, 1, 2, 3])
To remove the last element I simply provided a new shape that is 1 smaller than before, which effectively removes the last element.
Modifying the array inplace
Yes, I've written previously that you cannot modify an array in place. But I said that because in most cases it's not possible or only by disabling some (completely useful) safety checks. I'm not sure about the internals but depending on the old size and the new size it could be possible that this includes an (internal-only) copy operation so it might be slower than creating a view.
Using np.ndarray.resize()
If the array doesn't share its memory with any other array, then it's possible to resize the array in place:
>>> arr = np.arange(5, 10)
>>> arr.resize(4)
>>> arr
array([5, 6, 7, 8])
However that will throw ValueErrors in case it's actually referenced by another array as well:
>>> arr = np.arange(5)
>>> view = arr[1:]
>>> arr.resize(4)
ValueError: cannot resize an array that references or is referenced by another array in this way. Use the resize function
You can disable that safety-check by setting refcheck=False but that shouldn't be done lightly because you make yourself vulnerable for segmentation faults and memory corruption in case the other reference tries to access the removed elements! This refcheck argument should be treated as an expert-only option!
Summary
Creating a view is really fast and doesn't take much additional memory, so whenever possible you should try to work as much with views as possible. However depending on the use-cases it's not so easy to remove arbitrary elements using basic slicing. While it's easy to remove the first n elements and/or last n elements or remove every x element (the step argument for slicing) this is all you can do with it.
But in your case of removing the last element of a one-dimensional array I would recommend:
arr[:-1] # if you want a view
arr[:-1].copy() # if you want a new array
because these most clearly express the intent and everyone with Python/NumPy experience will recognize that.
Timings
Based on the timing framework from this answer:
# Setup
import numpy as np
def view(arr):
return arr[:-1]
def array_copy_view(arr):
return arr[:-1].copy()
def array_int_index(arr):
return arr[np.arange(arr.size - 1)]
def array_bool_index(arr):
if not arr.size:
raise IndexError('cannot remove last element of empty array')
keep = np.ones(arr.shape, dtype=bool)
keep[-1] = False
return arr[keep]
def array_delete(arr):
return np.delete(arr, -1)
def array_resize(arr):
return np.resize(arr, arr.size - 1)
# Timing setup
timings = {view: [],
array_copy_view: [], array_int_index: [], array_bool_index: [],
array_delete: [], array_resize: []}
sizes = [2**i for i in range(1, 20, 2)]
# Timing
for size in sizes:
print(size)
func_input = np.random.random(size=size)
for func in timings:
print(func.__name__.ljust(20), ' ', end='')
res = %timeit -o func(func_input) # if you use IPython, otherwise use the "timeit" module
timings[func].append(res)
# Plotting
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(1)
ax = plt.subplot(111)
for func in timings:
ax.plot(sizes,
[time.best for time in timings[func]],
label=func.__name__)
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel('size')
ax.set_ylabel('time [seconds]')
ax.grid(which='both')
ax.legend()
plt.tight_layout()
I get the following timings as log-log plot to cover all the details, lower time still means faster, but the range between two ticks represents one order of magnitude instead of a fixed amount. In case you're interested in the specific values, I copied them into this gist:
According to these timings those two approaches are also the fastest. (Python 3.6 and NumPy 1.14.0)
If you want to quickly get array without last element (not removing explicit), use slicing:
array[:-1]
To delete the last element from a 1-dimensional NumPy array, use the numpy.delete method, like so:
import numpy as np
# Create a 1-dimensional NumPy array that holds 5 values
values = np.array([1, 2, 3, 4, 5])
# Remove the last element of the array using the numpy.delete method
values = np.delete(values, -1)
print(values)
Output:
[1 2 3 4]
The last value of the NumPy array, which was 5, is now removed.
I was wondering whether there is a way to refer data from many different arrays to one array, but without copying it.
Example:
import numpy as np
a = np.array([2,3,4,5,6])
b = np.array([5,6,7,8])
c = np.ndarray([len(a)+len(b)])
offset = 0
c[offset:offset+len(a)] = a
offset += len(a)
c[offset:offset+len(b)] = b
However, in the example above, c is a new array, so that if you modify some element of a or b, it is not modified in c at all.
I would like that each index of c (i.e. c[0], c[1], etc.) refer to each element of both a and b, but like a pointer, without making a deepcopy of the data.
As #Jaime says, you can't generate a new array whose contents point to elements in multiple existing arrays, but you can do the opposite:
import numpy as np
c = np.arange(2, 9)
a = c[:5]
b = c[3:]
print(a, b, c)
# (array([2, 3, 4, 5, 6]), array([5, 6, 7, 8]), array([2, 3, 4, 5, 6, 7, 8]))
b[0] = -1
print(c,)
# (array([ 2, 3, 4, -1, 6, 7, 8]),)
I think the fundamental problem with what you're asking for is that numpy arrays must be backed by a continuous block of memory that can be regularly strided in order to map memory addresses to the individual array elements.
In your example, a and b will be allocated within non-adjacent blocks of memory, so there will be no way to address their elements using a single set of strides.