This is my first post here and I'm a python beginner - all help is appreciated!
I'm trying to add all combinations of adjacent rows in a numpy matrix. i.e. row 1 + row 2, row 2 + row 3, row 3 + row 4, etc... with output to a list
I will then look for the smallest of these outputs and select that item in the list to be printed
I believe I need to use a for loop of some sort but I really am a novice...
Just iterate over the length of the array - 1 and add the pairs as you go into a new list. Then, select the one you want. For example:
>>> x = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> print [x[i] + x[i+1] for i in range(len(x)-1)]
[array([5, 7, 9]), array([11, 13, 15])]
Suppose you have this
import numpy as np
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7 , 8, 9]])
You can first calculate the sum of each row by using np.sum(arr, axis=1) the argument axis=1 allows to sum each column entries for each line.
In this case, sums = np.sum(arr, axis=1) = array([ 6, 15, 24]).
Then you can iterate over this tab to add the different sums :
lst_sums = []
for s in range(len(sums)-1) :
lst_sums.append(sums[i]+sums[i+1])
Then you can sorted or getting the np.min(sums)
If you need more details you can look at numpy function docs, same for the lists
Related
I want to split my numpy array into separate arrays. The separation must be based on the index. The split count is given by the user.
For example,
The input array: my_array=[1,2,3,4,5,6,7,8,9,10]
If user gives split count =2,
then, the split must be like
my_array1=[1,3,5,7,9]
my_array2=[2,4,6,8,10]
if user gives split count=3, then
the output array must be
my_array1=[1,4,7,10]
my_array2=[2,5,8]
my_array3=[3,6,9]
could anyone please explain, I did for split count 2 using even odd concept
for i in range(len(outputarray)):
if i%2==0:
even_array.append(outputarray[i])
else:
odd_array.append(outputarray[i])
I don't know how to do the split for variable counts like 3,4,5 based on the index.
You can use indexing by vector (aka fancy indexing) for it:
>>> a=np.array([1,2,3,4,5,6,7,8,9,10])
>>> n = 3
>>> [a[np.arange(i, len(a), n)] for i in range(n)]
[array([ 1, 4, 7, 10]), array([2, 5, 8]), array([3, 6, 9])]
Explanation
arange(i, len(a), n) generates an array of integers starting with i, spanning no longer than len(a) with step n. For example, for i = 0 it generates an array
>>> np.arange(0, 10, 3)
array([0, 3, 6, 9])
Now when you index an array with another array, you get the elements at the requested indices:
>>> a[[0, 3, 6, 9]]
array([ 1, 4, 7, 10])
These steps are repeated for i=1..2 resulting in the desired list of arrays.
Here is a python-only way of doing your task
def split_array(array, n=3):
arrays = [[] for _ in range(n)]
for x in range(n):
for i in range(n):
arrays[i] = [array[x] for x in range(len(array)) if x%n==i]
return arrays
Input:
my_array=[1,2,3,4,5,6,7,8,9,10]
print(split_array(my_array, n=3))
Output:
[[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]
If I have an array: A = np.array([[1,2,0],[5,6,0]]). How can I replace the third column with the sum of the first two or some other arithmetic combination of the other columns?
In the example, calculating the third column as the sum of the sum of the first 2 would give: np.array([[1,2,3],[5,6,11]]).
I've tried A[:2] = A[:,0] + A[:,1] and A[:2] = A[:,0].T + A[:,1].T. I've searched for adding columns, but found ways to insert columns.
import numpy as np
A = np.array([[1,2,3],[5,6,7]])
A[:2] = A[:,0] + A[:,1]
In R this is very easy, but I don't see a simple way to do it in Python.
You're almost there:
>>> A[:,2] = A[:,0] + A[:,1]
>>> A
array([[ 1, 2, 3],
[ 5, 6, 11]])
In A[:, k]:
A is the array you're indexing
: as the first index means "all rows"
For instance, A[:, :] means "all rows and all columns"
k as the second index means "kth column"
For instance, A[1, 2] means "element at row 1, column 2"
A[2, :] means "row 2, all its columns"
This can be generalised to any number of dimensions.
slice array and equate to the sum along the row axis.
A[all rows,column 3]= sum of each row in array A
code below
A[:,2]=A.sum(1)
array([[ 1, 2, 3],
[ 5, 6, 11]])
In Python, I have a data set with several rows and columns. If the value of one column=X I am interested in the value of the row above it and the column to the right so plus [1,1] from the previous location of value x.
What's the best way to approach this? If cell =X, is there a dynamic way I can get the location and then add X amount of rows and columns to it "since I am interested in the value of that cell"?
Visual Example of Question
Say our array is defined as:
import numpy as np
arr = np.array([[9, 8, 4, 5, 2],
[0, 3, 5, 6, 7],
[6, 6, 2, 0, 6],
[2, 0, 2, 5, 8],
[2, 6, 9, 7, 9]])
A straight forward solution is to just loop through the column of interest.
colIndex = 2
X = 2
rDelta = -1 #row change, up is negative!
cDelta = 1 #col change, right is positive
numberRows = np.shape(arr)[1]
output = []
#This loops through all the values in the specified column and looks for
#matches, if a match is found it is added to an output list
#Note that we only look at values that would result in valid output
# for example we will not look at the first row if
# we would need to index into the row above for the output
for i in range(max(-rDelta,0),min(numberRows,numberRows-rDelta)):
if(arr[i,colIndex]==X):
#replace this with your processing
output.append(arr[i+rDelta,colIndex+cDelta])
After running this code I get that output as
[6, 0]
which are the values up and to the right of the 2's in the second column.
I need to extract one element from each column of a matrix according to an index vector. Say:
index = [0,1,1]
matrix = [[1,4,7],[2,5,8],[3,6,9]]
Index vector tells me I need the first element from column 1, second element from column 2, and third element from column 3.
The output should be [1,5,8]. How can I write it out without explicit loop?
Thanks
You can use advanced indexing:
index = np.array([0,1,2])
matrix = np.array([[1,4,7],[2,5,8],[3,6,9]])
res = matrix[np.arange(matrix.shape[0]), index]
# array([1, 5, 9])
For your second example, reverse your indices:
index = np.array([0,1,1])
matrix = np.array([[1,4,7],[2,5,8],[3,6,9]])
res = matrix[index, np.arange(matrix.shape[1])]
# array([1, 5, 8])
Since you're working with 2-dimensional matrices, I'd suggest using numpy. Then, in your case, you can just use np.diag:
>>> import numpy as np
>>> matrix = np.array([[1,4,7],[2,5,8],[3,6,9]])
>>> matrix
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
>>> np.diag(matrix)
array([1, 5, 9])
However, #jpp's solution is more generalizable. My solution is useful in your case because you really just want the diagonal of your matrix.
val = [matrix[i][index[i]] for i in range(0, len(index))]
I have 1D array in numpy, and I want to add a certain value to part of the array.
For example, if the array is:
a = [1, 2, 3, 4, 5]
I want to add the value 7 to 2nd and 3rd columns to get:
a = [1, 2, 10, 11, 5]
Is there any simple way to do this?
Thanks!
You can index the array with another array containing the indices:
a[[2,3]] += 7
If your columns have some pattern, like in this specific case, they are contiguous, then you can use fancy indexing:
a = np.array([1, 2, 3, 4, 5])
a[2:4] += 7
Note here 2:4 means "from column 2(included) to column 4(excluded)", thus it's column 2 and 3.