1

I have a .dat file with three columns separated by spaces [example shown below but in my case there are not column names], and I need to sort the other columns based on the phase column, which is being sorted from least to greatest.

For example,

Time    Phase    Mag 
t1      0.1      m1 
t2      0.0      m2
t3      0.2      m3
t4      0.4      m4
t5      0.3      m5

And then sort the three columns like this:

t2      0.0       m2
t1      0.1       m1 
t3      0.2       m3
t5      0.3       m5
t4      0.4       m4

I found an example for 2 column data, 2 column sorting example, but it doesn't work for 3 columns. Can someone help me with this?

jenn
  • 11
  • 3
  • You can read the file into a dataframe, and sort it on the column `phase`. – gaganso Jul 13 '18 at 00:10
  • Possible duplicate of [how to sort pandas dataframe from one column](https://stackoverflow.com/questions/37787698/how-to-sort-pandas-dataframe-from-one-column) – gaganso Jul 20 '18 at 21:37

1 Answers1

0

I have saved the below contents to a file called example.dat

Time    Phase    Mag 
t1      0.1      m1 
t2      0.0      m2
t3      0.2      m3
t4      0.4      m4
t5      0.3      m5

The below code should do the job.

import pandas as pd

df = pd.read_csv("example.dat",delim_whitespace=True) # read the file with whitespaces as the delimiter
df.sort_values("Phase") # sort on the column "Phase"

Output:

    Time Phase  Mag
1   t2   0.0    m2
0   t1   0.1    m1
2   t3   0.2    m3
4   t5   0.3    m5
3   t4   0.4    m4
gaganso
  • 2,914
  • 2
  • 26
  • 43
  • Thanks! This was very helpful. I also found that there was an extra space at the beginning of the file which resulted in a keyerror, so I used this: `df = pd.read_csv('filename.dat', delim_whitespace=True, encoding="utf-8-sig") df.sort_values("PHASE")` – jenn Jul 13 '18 at 01:56
  • That's great! If it helped, please accept/upvote the answer. – gaganso Jul 13 '18 at 02:03
  • 1
    I did but since I am a new member, it won't show until I have a higher 'reputation.' – jenn Jul 13 '18 at 02:52