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

sorting DataFrame by columns using python

Suppose I have a dataframe

df =
| CHROM | 
| ------| 
| chr1  | 
| chr5  |
| chr12 |
| chr9  |
| chr3  |

I have used this code to sort them:

sorted_df = df.sort_values(by=["CHROM"])

I got the result,

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

| CHROM | 
| ------| 
| chr1  | 
| chr12 |
| chr3  |
| chr5  |
| chr9  |

But, My expected output

| CHROM | 
| ------| 
| chr1  | 
| chr3  |
| chr5  |
| chr9  |
| chr12 |

Please suggest how to do using python

>Solution :

You can split base "chr" then sort the base number as int and find the index and return df with the sorted index.

idx = df["CHROM"].str.split('chr').str[-1].astype(int).sort_values().index
df_new = df.iloc[idx]
print(df_new)

Or You can use pandas.DataFrame.sort_values with key.

df.sort_values(by=['CHROM'], 
               key=lambda x: df['CHROM'].str.split('chr').str[-1].astype(int))

Output:

   CHROM
0   chr1
4   chr3
1   chr5
3   chr9
2  chr12
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