Richard Rublev Richard Rublev - 6 months ago 10
Python Question

Sorting one array by another in Python

I have a file with 200000 lines,the third column is velocity which should be sorted.I am just giving first 20 lines

second.txt

0 0 1.200000
0 1 1.200000
0 2 1.200000
0 3 1.200000
0 4 1.200000
0 5 1.200000
0 6 1.200000
0 7 1.200000
0 8 1.200000
0 9 1.200000
0 10 1.200000
0 11 1.200000
0 12 1.200000
0 13 1.200000
0 14 1.200000
0 15 1.200000
0 16 1.200000
0 17 1.200000
0 18 1.200000
0 19 1.200000


Array which should be used as a reference

newindex1.txt

0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
11 0
12 0
13 0
14 0
15 0
16 0
17 0
18 0
19 0


What I want is to take third column value and place it to appropriate
newindex1.txt
index pair.

Desired output

0 0 1.200000
1 0 1.200000
2 0 1.200000
3 0 1.200000
4 0 1.200000
5 0 1.200000
6 0 1.200000
7 0 1.200000
8 0 1.200000
9 0 1.200000
10 0 1.200000
11 0 1.200000
12 0 1.200000
13 0 1.200000
14 0 1.200000
15 0 1.200000
16 0 1.200000
17 0 1.200000
18 0 1.200000
19 0 1.200000


All examples are just 20 lines,real files are huge.

I have tried this

import numpy as np
from numpy import loadtxt
from operator import itemgetter

s = loadtxt("second.txt", delimiter=" ", unpack=False)
ni = loadtxt("newindex1.txt", delimiter=" ", unpack=False)

for i, l in enumerate(ni):
for m,n,v in s:
s[m,n,v] == ni[i,l]


It does not work

s[m,n,v] == ni[i,l]
IndexError: too many indices


Any ideas how to solve this?

Answer

In case the newindex1.txt is sorted by an unknown rule, I think you might use a dict to get a velocity by an index ():

import numpy as np
from numpy import loadtxt
from operator import itemgetter

s = loadtxt("second.txt", delimiter=" ", unpack=False)
ni = loadtxt("newindex1.txt", delimiter=" ", unpack=False)

index = {}

for m,n,v in s:
    index [str (m) + '_' + str (n)] = v

for i,l in ni:
    key = str (i) + '_' + str (l)

    if key in index.keys ():
        print (i, l, index [key])
Comments