1

I have a txt file containing 2 columns that are not ordered:

1 0.1
4 0.5
3 0.2

To order it for plotting, i found that i could that i could open the file and use zip function such as :

    data=np.loadtxt(file)
    x=data[:, 0]
    y = data[:, 1]
    x, y = zip(*sorted(zip(x, y)))

It works well but it doesn't actually modify the file and make the replacement to get the final output :

1 0.1
3 0.2
4 0.5
4
  • Does this answer your question? Correct way to write line to file? Commented Aug 3, 2022 at 13:18
  • numpy has a function for writing text files: numpy.org/doc/stable/reference/generated/numpy.savetxt.html Commented Aug 3, 2022 at 13:19
  • In order to modify a file, you must write the data to the file. It also looks, from you desired output, that all you really need to do is sort the data on the first column. Not sure why you need the zip function. Commented Aug 3, 2022 at 13:21
  • i have a function f(x) so if i need to sort x columns in order and the y values changes according to the sorting of x. Commented Aug 3, 2022 at 13:23

1 Answer 1

1
import pandas as pd
data = pd.read_csv("data.txt", sep=' ', header=None)
data.sort_values(by=0).to_csv('data.txt', index=False, header=False, sep=' ')

or with lovely polars (similar to pandas but faster:)):

import polars as pl
data = pl.read_csv("data.txt", sep=' ', has_header=False)
data.sort(by="column_1").write_csv('data.txt', has_header=False, sep=' ')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.