Let's say I want to iterate over a numpy array and print each item. I'm going to use this later on to manipulate the (i,j) entry in my array depending on some rules.
I've read the numpy docs and it seems like you can access individual elements in an array easily enough using similar indexing(or slicing) to lists. But it seems that I am unable to do anything with each (i,j) entry when I try to access it in a loop.
row= 3
column = 2
space = np.random.randint(2, size=(row, column))
print space, "\n"
print space[0,1]
print space[1,0] #test if I can access indiivdual elements
output:
[[1,1
[1,1
[0,0]]
1
1
for example, using the above I want to iterate over every row and column and print each entry. I would think to use something like the following:
for i in space[0:row,:]:
for j in space[:,0:column]:
print space[i,j]
the output I get is
[1,1]
[1,1]
[1,1]
[1,1]
[1,1]
[1,1]
[1,1]
[1,1]
[1,1]
Obviously this does not work. I believe the problem is that I'm accessing entire rows and columns instead of elements within any given row and column. I've been going over the numpy docs for a couple of hours and I am still unsure of how to go about this.
My main concern is I want to change each (i,j) entry by using a loop and some conditionals, for example (using the above loop):
for i in space[0:row,:]:
for j in space[:,0:column]:
if [i+1,j] + [i,j+1] == 2:
[i,j] = 1
Start with:
for i in range(row):
for j in range(column):
print space[i,j]
You are generating indices in your loops which index some element then!
The relevant numpy docs on indexing are here.
But it looks, that you should also read up basic python-loops.
Start simple and read some docs and tutorials. After i saw Praveen's comment, i felt a bit bad with this simple answer here which does not offer much more than his comment, but maybe the links above are just what you need.
A general remark on learning numpy by trying:
regularly use arr.shape to check the dimensions
regularly use arr.dtype to check the data-type
So in your case the following should have given you a warning (not a python one; one in your head) as you probably expected i to iterate over values of one dimension:
print((space[0:row,:]).shape)
# output: (3, 2)
There are many ways of iterating over a 2d array:
In [802]: x=np.array([[1,1],[1,0],[0,1]])
In [803]: print(x) # non-iteration
[[1 1]
[1 0]
[0 1]]
by rows:
In [805]: for row in x:
...: print(row)
[1 1]
[1 0]
[0 1]
add enumerate to get an index as well
In [806]: for i, row in enumerate(x):
...: row += i
In [807]: x
Out[807]:
array([[1, 1],
[2, 1],
[2, 3]])
double level iteration:
In [808]: for i, row in enumerate(x):
...: for j, v in enumerate(row):
...: print(i,j,v)
0 0 1
0 1 1
1 0 2
1 1 1
2 0 2
2 1 3
of course you could iterate on ranges:
for i in range(x.shape[0]):
for j in range(x.shape[1]):
x[i,j]...
for i,j in np.ndindex(x.shape):
print(i,j,x[i,j])
Which is best depends, in part, on whether you need to just use the values, or need to modify them. If modifying you need an understanding of whether the item is mutable or not.
But note that I can remove the +1 without explicit iteration:
In [814]: x-np.arange(3)[:,None]
Out[814]:
array([[1, 1],
[1, 0],
[0, 1]])
Related
I am learning python numpy.array and am confused about how the index works. Let's see I have the following 3x4 2D array:
A = np.array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9,10,11,12]])
If I want to extract the 1 from this array, I need to input the index of that number, which is A[0,0]
Out of curiosity I also tried the following
B = A[[0,0]]
C = A[[0],[0]]
B turns out to be a 2x4 2D array:
array([[1, 2, 3, 4],
[1, 2, 3, 4]])
C turns out to be a 1D array of 1 element:
array([1])
I am wondering how indexing of B and C works and why I obtain those arrays?
In B, you are only giving one index for a 2 dimensional array which is [0,0]. So it will return the element in the first dimension of the index given (0 and 0 here).
So, for the first index (which is 0) it will return the first element in the first dimension which is [1,2,3,4] and it will go for the next index given which is again 0, so it will print two [1,2,3,4] as you have got.
Next in the C, you have given 2 indices for a 2 dimensional array which are [0] and [0]. So it will go through the first dimension for the index 0 which is [1,2,3,4] and in that element it will return the 0th position which is [1] as you have got.
For better understanding, let's see another case A[[0,1],2].
Here, we have given 2 indices for a 2 dimensional array which are [0,1] and 2. So, we get the elements which are in the index [0,2] and next with [1,2].Th output will be [3,7].
The thing is it will iterate through all possible combinations of indices given and return those values in those indices.
So I have two arrays. For each element in column i in array_1, I want to find whether the same element exists in column i in array_2. If it exists, I want the corresponding position/index in column i in array_2. If it doesn't exist, return False.
Instead of using for loop, I am wondering if there is any vectorized function that would do this task efficiently?
Below are two sample arrays and my desired output.
array_1 = np.array([[1, 2], [2 , np.nan]])
array_2 = np.array([[2, np.nan], [1 , 3 ]])
My desired output:
np.array([[1, False], [0 , 0]])
mean = [0, 0]
cov = [[1, 0], [0, 100]]
gg = np.random.multivariate_normal(mean, cov, size = [5, 12])
I get an array which has 2 columns and 12 rows, i want to take the first column which will include all 12 rows and convert them to columns. What is the appropriate method for sclicing and how can one convet the result to columns? To be precise, looking at the screen (the second one) one should take all 0 column columns and convert them in a normal way from the left to the right
the results should be like this (the first screen)
The problem is that your array gg is not two- but three-dimensional. So, what you need is in fact the first column of each stacked 2D array. Here is an example:
import numpy as np
x = np.random.randint(0, 10, (3, 4, 5))
x[:, :, 0].flatten()
The colon in slicing means "all values in this dimension". So, x[:, :, 0] means "all values in the the first dimension and all values in the second dimension and with third dimension fixed on index 0". This results in a two-dimensional array, which you have to flatten additionally.
I am having trouble understanding what seems like an inconsistent behavior in Julia.
X = reshape(1:100, 10, 10)
b = [1 5 9]
X[2, :][b] # returns the correct array
X[2, :][1 5 9] # throws an error
Can someone explain why using the variable b works to index an array but not when I write the index myself?
Since x = X[2,:] is just a vector, we can simplify the example to just talking about indexing behavior on vectors.
x[v] where v is a collection of integers returns the subset of x. Thus x[(1,5,9)], or x[[1,5,9]] is thus using that getindex(x::Vector,i::AbstractArray) dispatch.
Note that x[[1 5 9]] works because v = [1 5 9] makes v a row vector. That's valid syntax, but x[1 5 9] just isn't even valid Julia syntax. That syntax means something else:
v = Float64[1 5 9]
returns a row vector with element type Float64.
I have figured out a solution.
Rather than write X[2, :][1 5 9] I should have written x[2, :][[1 5 9]]
I believe this makes sense when we imagine indexing on two dimensions the second time. This makes it possible to write more complicate indices, like X[2:4, :][[1 3],[1 3]]
im doing a project and this part is rly important to me.i'll try to be as clear as possible.
suppose we have an mxn matrix with all 0s, i need to generate all possible combinations of the array in which only one element in a row is initialised to 1 and all the other elements in that row are 0s. similarly, in all the rows, exactly one element should be 1. ex: take a 3x2 matrix, the following should be the output:
[1 0,1 0,1 0], [1 0, 1 0,0 1], [1 0,0 1,1 0], [1 0, 0 1, 0 1], [0 1, 1 0,1 0], [0 1, 1 0, 0 1], [0 1, 0 1, 1 0], [0 1, 0 1, 0 1]
the values within the square brackets is a 3x2 matrix,each row separated by a comma. so basically, an mxn matrix will have n power m number of combinations.
anyone who can think of any possible way of solving this pls post it, its really important. thanks in advance
Since this sounds like homework I'm not going to give you a complete solution, but rather some steps in the right direction. Let's start with a 3x2 matrix. We can solve this using nested for loops:
int row0, row1, row2;
for(row0=0; row0<2; ++row0) {
matrix[0][row0] = 1;
for(row1=0; row1<2; ++row1) {
matrix[1][row1] = 1;
for(row2=0; row2<2; ++row2) {
matrix[2][row2] = 1;
print_matrix(matrix);
matrix[2][row2] = 0;
}
matrix[1][row1] = 0;
}
matrix[0][row0] = 0;
}
Of course this isn't a very generic solution. It's easy to change this to a 3xm matrix (just replace the row#<2 with row#<m-1) but clearly this doesn't work for an nxm matrix. Everytime we increase n by one we need to add another for loop.
I leave it up to you to determine how to get rid of the nested for loops and use some other technique to generalize it.