Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reordering lines in a txt file with Python

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1 0.1
3 0.2
4 0.5

>Solution :

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=' ')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading