Reputation: 109
I have defined a function in Python which reads data from a non-sorted text file, sort the content by increasing order. I then ask the function to return the final variable.
When I call the function as part of another script the output of the function is in the "unsorted" state.
def read_file(my_file):
import numpy as np
initial_data =[]
A = []
B = []
C = []
D = []
with open(my_file) as f:
for num, row in enumerate(f):
initial_data.append(row[:])
lines = row.strip()
columns = lines.split()
if num > 11:
A.append(float(columns[0]))
B.append(float(columns[1]))
C.append(float(columns[2]))
D.append(float(columns[4]))
data = np.vstack((A,B, C,D)).T
data= data[np.argsort(data[:,0])]
return(data)
When i run this script alone the final data
is sorted as per data[np.argsort(data[:,0])]
.
But when I do:
new_data = read_file(my_file)
new_data
is not sorted.
EDIT: I am using Python 3, my_file
is a simple text file (.txt)
Upvotes: 0
Views: 87
Reputation: 296
Actually, I don't know the reason for this, but I face the same problem and I know how to pass it. I solve the problem by replacing the "data" in the last line with new numpy array. I mean instead of this line
data= data[np.argsort(data[:,0])]
replace this two lines code
data1 = np.zeros(data.shape)
data1 = data[np.argsort(data[:,0])]
and finally return the data1.
Upvotes: 1