I have some data array
a = [6,4,3,1,5]
and a "to location array", that gives indices for how these elements should be reshuffled,
b = [4,2,0,1,3]
What this means: the 1st element of a should go to index 4, the 2nd element of a should go to index 2, and so on. So when applying b to a, I should get:
c = [3,1,4,5,6]
However, I am struggling to implement this operation. Is it a common operation? If so, could someone give me an example? I want to generate some array d from b so that
c = a[d]
In the above example,
d = [2,3,1,4,0]
What I tried: d = b[b], but this is not always correct.
If you don't need d, you can directly get c with np.put_along_axis:
>>> a = np.array([6,4,3,1,5])
>>> b = np.array([4,2,0,1,3])
>>> c = np.zeros_like(b)
>>> np.put_along_axis(c, b, a, 0)
>>> c
array([3, 1, 4, 5, 6])
Note the operation is inplace.
One method I just found is calculating d is as follows:
d = np.zeros(5);
d[b] = np.arange(5)
But it seems very non-intuitive to me.
Related
I have numpy array:
A = np.array([1,3,5,7,9])
and
B = np.array([3,3,3,5,5,5])
I want to have array C - which is index B in A.
C = np.array([1,1,1,2,2,2])
How I can do it?
The function searchsorted provides exactly the functionality you need.
C = np.searchsorted(A, B)
Say I have:
data = [[1, 2], [3, 4]]
And I want to define a function that will take this one list argument, 'data', and be able to separate the integers within the first and second instances.
After, it needs to take each of those integers that shared each instance and subtract it from one another like this:
1 - 2 (which would be -1)
3 - 4 (which would be -1)
And then take those numbers and finds the product and returns the final integer (-1 * -1) = 1
Kind of lost as to how I would go about this.
You can do this easily with unpacking:
data = [[1, 2], [3, 4]]
d1, d2 = data
a, b, c, d = *d1, *d2
res = (a - b) * (c - d)
print(res)
# 1
If there are arbitrary number of sublists, you would better iterate:
lst = []
for d in data:
a, b = d
lst.append(a - b)
res = 1
for x in lst:
res *= x
print(res)
# 1
I have an array like this:
A = [[1,0,2,3],
[2,0,1,1],
[3,1,0,0]]
and I want to get the position of one of the cells with the value == 1 such as A[0][0] or A[1][2] and so on ...
So far I did this:
A = np.array([[1,0,2,3],
[2,0,1,1],
[3,1,0,0]])
B = np.where(A == 1)
C = []
for i in range(len(B[0])):
Ca = [B[0][i], B[1][i]]
C.append(Ca)
D = random.choice(C)
But now I want to reuse D for getting a cell value back. Like:
A[D] (which does not work) should return the same as A[1][2]
Does someone how to fix this or knows even a better solution?
This should work for you.
A = np.array([[1,0,2,3],
[2,0,1,1],
[3,1,0,0]])
B = np.where(A == 1)
C = []
for i in range(len(B[0])):
Ca = [B[0][i], B[1][i]]
C.append(Ca)
D = random.choice(C)
print(A[D[0]][D[1]])
This gives the output.
>>> print(A[D[0]][D[1]])
1
Since the value of D would be of the sort [X,Y], the value could be obtained from the matrix as A[D[0]][D[1]]
It seems you are trying to randomly select one of the cells where A is 1. You can use numpy for this all the way through instead of having to resort to for-loops
B = np.array(np.where(A == 1))
>>> B
array([[0, 1, 1, 2],
[0, 2, 3, 1]])
Now to randomly select a column corresponding to one of the cells, we can use np.random.randint
column = np.random.randint(B.shape[1])
D = B[:, column]
>>> D
array([1, 2]) # corresponds to the second index pair in B
Now you can simply index into A using the tuple of D (to correpond to the dimensions' indices) as
>>> A[tuple(D)]
1
Example, I have the following lists in Python
A = [1,2,3]
B = [4,5,6]
I would need to create a new list C such that the elements should be paired as a separate lists based on their index numbers. i.e., C = [[[1,4],[2,5],[3,6]], [[1,4],[2,5],[3,6]]]
I have written a code to that but it is purely structured. Can you please provide if there is any better way other than the below code?
A = [1,2,3]
B = [4,5,6]
D = [a,b,c]
E = [d,e,f]
C = []
list = []
for i in range(len(A)):
list.append([A[i],B[i]])
C.append(list)
list = []
for i in range(len(D)):
list.append([D[i],E[i]])
C.append(list)
I have to repeat this code if I have multiple cases similar to the above one in my code. Which is poor in structuring.
Can someone suggest any better method for the problem?
You can use zip, convert that to list
list(zip(a,b))
which will give list of tuples. If you want list of lists, you can go:
[[i,j] for i,j in zip(a,b)]
You can try something like this in one line.
C = [[A[i],B[i]] for i in range(len(A))]
Be careful if A and B don't have the same length though!
Your problem has a simple solution found in Python's built-in functions,
The 'zip' function takes 2 arguments (iterables) and return a single iterator.
Here is an example code:
a = [1, 2, 3]
b = [4, 5, 6]
c = list(zip(a, b))
# c -> [(1, 4), (2, 5), (3, 6)]
# if you want the elements to be list instead of tuple you can do
c = [[i, j] for i,j in zip(a, b)]
# c -> [[1, 4], [2, 5], [3, 6]]
you can use zip for this
c= zip(a,b)
c=list(c)
if you convert in set then
c=set(c)
Using numpy, the following would be efficient.
import numpy as np
A = [1,2,3]
B = [4,5,6]
a = np.array(A)
b = np.array(B)
c = np.vstack((a, b)).T
print c
C = c.tolist()
print C
lower case letters are all numpy arrays, upper case are python arrays
I have some data looks like in this format
2,3,4
3,4,5
5,6,7
I pack the array as:
with open('house_price_data.txt') as data:
substrings = data.read().split()
array = [map(int, substring.split(',')) for substring in substrings]
My task is to do some calculation like this for each data in the set:
(2-3)**2 + (3-3)**2 + (5-3)**2
(3-4)**2 + (4-4)**2 + (5-4)**2
My expected answer is C1 = 5 and C2 = 2
I wrote a code like this
for [a for a, b, c in array] in range (0,2):
C1 = (([a for a, b, c in array]) - 3)**2
C2 = (([b for a, b, c in array]) - 4)**2
But it is not working. For the purpose of for loop, I think it will read the data 2,3,5 one by one minus 3 and square the result one by one and sum the total results. So how can I improve it?
A part from that, I also have problems with this code
[a for a, b, c in array]
[b for a, b, c in array]
[c for a, b, c in array]
I need to call array many times with this code with item a, b and c of the array in the program, when I have such codes in the program error massage come
not enough values to unpack (expected 3, got 0)
How can I do to make changes?
This question is unclear and probably destined for oblivion, but if I understand correctly, which is far from certain, you are trying to do something like this.
array = [[2, 3, 5], [3, 4, 5], [5, 6, 7]]
#initialize the variables C1 and C2
C1 = 0
C2 = 0
#iterate the elements of the FIRST list in your list
#so 2,3,5 (I assume you have indicated 2,3,4 by mistake)
for element in array[0]:
C1+=(element-3)**2
#iterate the elements of the SECOND list in your list
#so 3,4,5
for element in array[1]:
C2+=(element-4)**2
print("C1 =", C1)
print("C2 =", C2)
Output:
C1 = 5
C2 = 2
But your example is ambiguous. Maybe 2,3,5 are the first elements in each sublist ? In this case, the logic is the same.
#iterate the FIRST element in each sublist in your list
for element in array:
C1+=(element[0]-3)**2
If that's what you want to do, then it's best for you to do it like that, with classic loops. List comprehensions (things like [x for x in array if ...]) are shortcuts for advanced Python programmers. They do exactly the same thing, but are less clear and more error prone.
If you have array = [[2,3,4],[3,4,5],[5,6,7]], then you want a = [2,3,5], then that would be
a = [x[0] for x in array]
Otherwise, array[0] is [2,3,4] and you can instead do
a, b, c = array
To unpack the 2D array.
Sidenote: you seem to have a CSV file, so I would strongly suggest using Pandas and Numpy for your numerical calculations