This question already has answers here:
Difference between numpy.array shape (R, 1) and (R,)
(8 answers)
Closed 6 years ago.
I have an array converted from list, when I try to get its shape, I got only one number. like this:
list1=[1,2,3,4,5]
a1=numpy.array(list1)
print a1.shape
and I got
(5,)
and then I tried
list2=[[1,2,3,4,5]]
a2=numpy.array(list2)
list3=[[1],[2],[3],[4],[5]]
a3=numpy.array(list3)
print a1+a2
print a1+a3
I get
[[ 2 4 6 8 10]]
[[ 2 3 4 5 6]
[ 3 4 5 6 7]
[ 4 5 6 7 8]
[ 5 6 7 8 9]
[ 6 7 8 9 10]]
it seems a1 works like a2. Can I think like that way? Will it cause problems if i treat a1 as a2, besides shape method?
Try:
list1=[[1,2,3,4,5]]
a=numpy.array(list1)
print a.shape
This will give you (1, 5), one row, 5 columns.
And this:
list1=[[1],[2],[3],[4],[5]]
a=numpy.array(list1)
print a.shape
Will get you (5, 1)
You can look at this post, it has clarified every thing related to numpy shape. (edit: question marked as duplicate of the same question)
This simple code might also help you get some insights:
import numpy as np
list1=[1,2,3,4,5]
a=np.array(list1)
print a.shape
# (5,)
## set be to be the transpose of a
b = a.T
print b.shape
# (5,)
print np.inner(a,b)
# 55
print np.inner(a,a)
# 55
Related
This question already has answers here:
What is the difference between resize and reshape when using arrays in NumPy?
(5 answers)
What does it mean "The reshape function returns its argument with a modified shape, whereas the ndarray.resize method modifies the array itself"?
(3 answers)
Closed 2 years ago.
I was writing a line of code and I get some strange output of it.
a = np.arange(2,11).resize((3,3))
print(a)
a = np.arange(2,11).reshape((3,3))
print(a)
the first one gives me None but the second one gives me a 3X3 matrix.
but when I write the first code in separate lines it won't give me None
a = np.arange(2,11)
a.resize((3,3))
print(a)
what is the difference between resize and reshape in this case and in what are the differences in general?
That is because ndarray.resize modifies the array shape in-place, and since you're assigning back to a you get None, as an in-place operation does not return anything. reshape instead returns a view of the array:
a = np.arange(2,11)
a.shape
#(10,)
a.resize((3,3))
a.shape
# (3, 3)
np.arange(2,11).reshape((3,3)).shape
# (3, 3)
Both reshape and resize change the shape of the numpy array; the difference is that using resize will affect the original array while using reshape create a new reshaped instance of the array.
Reshape:
import numpy as np
r = np.arange(16)
print('original r: \n',r)
print('\nreshaped array: \n',r.reshape((4,4)))
print('\narray r after reshape was applied: \n',r)
output
original r:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
reshaped array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
array r after reshape was applied:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
Resize:
import numpy as np
r = np.arange(16)
print('original r: \n',r)
print('\nresized array: \n',r.resize((4,4)))
print('\narray r after resize was applied: \n',r)
output:
original r:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
resized array:
None
array r after resize was applied:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
As you can see reshape created a reshaped new instance of the data while the original r stayed unchanged.And As you can see, resize didn’t create a new instance of r, the changes were applied to the original array directly.
I am new to python, and I am stuck on a basic question. I want to enter a matrix:
[1 2 3
4 5 6
10 9 1]
but I want it to be in the form:
[[1,2,3], [4,5,6],[10,9,1]]
Do these representations have any specific names? What does that comma and double square brackets denote? I know this is a really silly question, but how do you convert it to the desired form?
Two ways:
1) Plain python
First step: Generate a list of 9 numbers
import random
randomlist = []
for i in range(0, 9):
n = random.randint(1, 30) # change for the value you desire here... for the moment it will give you a random numbers btween 0 to 9
randomlist.append(n)
print(randomlist)
Second step: make it to desired reshape (list of three lists) :
desiredoutput = [randomlist[x:x+3] for x in range(0, len(randomlist), 3)]
print(desiredoutput)
2) Using numpy
Reproduce the first step of solution 1 to get an array of random numbers. Then:
import numpy
sourcelist = numpy.asarray(randomlist)
desiredoutput = sourcelist.reshape(3, 3)
What you want to use is python numpy library which allows you to reshape your arrays into a form you want, not python lists
import numpy as np
a = np.asarray([1, 2, 3, 4, 5, 6, 9, 10, 1])
print(a)
# [ 1 2 3 4 5 6 9 10 1]
b = a.reshape(3, 3)
print(b)
# [[ 1 2 3]
# [ 4 5 6]
# [ 9 10 1]]
I'm trying to index a 2-dimensional array to certain values using numpy.where(), but unless I am indexing in the first index without a : slice it always increases the dimension. I can't seem to find an explanation for this in the documentation.
For example, say I have an array a:
a = np.arange(20)
a = np.reshape(a,(4,5))
print("a = ",a)
print("a shape = ", a.shape)
Output:
a = [[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
a shape = (4, 5)
If I have two indexing arrays, one in the 'x' direction and one in the 'y' direction:
x = np.arange(5)
y = np.arange(4)
xindx = np.where((x>=2)&(x<=4))
yindx = np.where((y>=1)&(y<=2))
and then index a using the 'y' index like so there's no problem:
print(a[yindx])
print(a[yindx].shape)
Output:
[[ 5 6 7 8 9]
[10 11 12 13 14]]
(2, 5)
But if I have : in one of the indices then I have an extra dimension of size 1:
print(a[yindx,:])
print(a[yindx,:].shape)
print(a[:,xindx])
print(a[:,xindx].shape)
Output:
[[[ 5 6 7 8 9]
[10 11 12 13 14]]]
(1, 2, 5)
[[[ 2 3 4]]
[[ 7 8 9]]
[[12 13 14]]
[[17 18 19]]]
(4, 1, 3)
I run into this issue with one-dimensional arrays, too. How do I fix this?
If xindx and yindx were numpy arrays, the result would be as expected. However, they are tuples with a single value.
Easiest (and pretty dumb) fix:
xindx = np.where((x>=2)&(x<=4))[0]
yindx = np.where((y>=1)&(y<=2))[0]
With only the condition given, np.where will return indices of matching elements in a tuple. This use is explicitly discouraged in the documentation.
More realistically, you probably need something like:
xindx = np.arange(2, 5)
yindx = np.arange(1, 3)
... but it really depends on the context we don't see
This question already has answers here:
numpy.random.shuffle returns None
(4 answers)
Closed 3 years ago.
while using the numpy.random.shuffle in my own function, it accidentally changed my global variable. I'm not sure if it is there some misunderstanding on its usage.
The numpy version is '1.16.4'
import numpy as np
def shuffle_test(a):
np.random.shuffle(a)
b=a
return b
outer_input = np.array(range(10))
print(outer_input)
outer_output = shuffle(outer_input)
print(outer_input)
Here's the result
input before shuffle:
[0 1 2 3 4 5 6 7 8 9]
input after shuffle:
[5 4 7 1 8 2 6 0 9 3]
It is not accidental; it is the described behavior of np.random.shuffle
Modify a sequence in-place by shuffling its contents
you could do like this:
import numpy as np
outer_input = np.array(range(10))
np.random.shuffle(outer_input)
outer_input
# array([1, 9, 7, 4, 3, 6, 0, 5, 2, 8]) # for instance
I have a list of Numpy arrays with the same shape (but not necessarily the same dtype) and I want to iterate over the elements of all the arrays at the same time. For instance, if the arrays are:
>>> a = np.array([[1,2,3], [4,5,6]])
>>> b = np.array([['one','two','three'],['four','five','six']])
I want the iteration over [a, b] to yield
[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five'), (6, 'six')]
I have found that numpy.nditer does almost what I need. This works:
>>> for x, y in np.nditer([a, b]):
... print('{} {}'.format(x, y))
1 one
2 two
3 three
4 four
5 five
6 six
Note that the iterator yields tuples of scalars:
>>> next(np.nditer([a, b]))
(array(1), array('one', dtype='<U5'))
However, in the corner case of a list containing one array,np.nditer directly yields the array elements:
>>> next(np.nditer([a]))
array(1)
I need it to yield a tuple with one element because I am unpacking the iterated values in the arguments of a function within the loop.
How do I convince np.nditer to yield a one-element tuple when iterating over a list of one array?
One workaround would be np.atleast_1D:
a = sum(np.ogrid[2:4, 3:5])
b = 2*a
for z in map(np.atleast_1d, np.nditer([a, b])):
print(np.arange(*z))
#[5 6 7 8 9]
#[ 6 7 8 9 10 11]
#[ 6 7 8 9 10 11]
#[ 7 8 9 10 11 12 13]
for z in map(np.atleast_1d, np.nditer([a])):
print(np.arange(*z))
#[0 1 2 3 4]
#[0 1 2 3 4 5]
#[0 1 2 3 4 5]
#[0 1 2 3 4 5 6]
Note that this unpacks the 0D arrays nditer returns into proper scalars. Also, it yields arrays, not tuples but as you just want to splat them to a function it shouldn't matter.
That goes against the behaviour of nditer.
Maybe you can always supply an array of None so that you always get a tuple? You have to handle the None in the function though.