Reputation: 5117
I am trying to index a numpy array with custom index. I understand that index can only be integers.
Some of the two number pair that I have looks like:
400, 200
300, 100
500, 60
I want to generate unique integers from this pair so that I could use them to index a numpy array. Like,
npArray[400200, 1] = someVal
npArray[300100, 2] = someOtherVal
The problem is, the size of my numpy array is only 4000 * 2. How can I generate unique identifiers from those pairs that falls into this 4000 range?
Thanks in advance.
Upvotes: 1
Views: 205
Reputation: 9795
As far as I understand your question, you are looking for a way to create a function one-to-one in order to generate one integer using two other ones. Look at the picture below, this is a function that implements it:
Speaking about Python implementation, here's my code for it (for Python 3.x):
def pack(i1, i2):
if i1 > i2:
return i1**2 + i2
else:
return (i2 + 1)**2 - 1 - i1
def unpack(i):
mx = int(i**0.5)
s = (mx**2 + (mx + 1)**2 - 1) // 2
if s >= i:
return mx, mx - s + i
else:
return mx - i + s, mx
i = pack(3, 5)
print(i) # 32
i1, i2, = unpack(i)
print(i1, i2) # 3 5
print(pack(400, 200)) # 160200
print(unpack(160200)) # (400, 200)
print(pack(300, 100)) # 90100
print(unpack(90100)) # (300, 100)
print(pack(500, 60)) # 250060
print(unpack(250060)) # (500, 60)
This index in unique because I always am able to calculate initial two integers.
Upvotes: 5
Reputation: 495
You could create an intermediate index and use that index value for numpy array:
List1 = [400,300,500,400]
List2= [200,100,60,200]
zipList = list(set(zip(List1,List2)))
def getIndex(Val1,Val2):
a = zipList.index((Val1,Val2))
return a
print getIndex(400,200)
Answer: 2
This 2 can now be used to index the array. zipList[2] will return (400,200). The values will be integers and always be unique.
Upvotes: 0