0

I have the following rows in Excel:

enter image description here

How can I put them in an ascending order in Python (i.e. notice how the row starting with 12 comes before that starting with 118).

I think the Pandas library would be a starting point? Any clue is appreciated.

Thanks.

Simplicity
  • 47,404
  • 98
  • 256
  • 385

2 Answers2

3

First read the excel file

df = pd.read_excel("your/file/path/file.xls")
df
         data   
0  1212.i.jpg  
1   121.i.jpg  
2   212.i.jpg  
3   512.i.jpg  

then make a substring of the data assuming the column name is "data"

df["sub"] = df["data"].str[:-6]

Just in case, convert the new column to type int

df["sub"] = df["sub"].astype(int)

Now sort the values, by that new column

df.sort_values("sub", inplace=True)

Finaly, if you only want your original data:

df = df["data"]


1     121.i.jpg
2     212.i.jpg
3     512.i.jpg
0    1212.i.jpg
2

Using natsorted

from natsort import natsorted
df.data=natsorted(df.data)
df
Out[129]: 
         data
0   121.i.jpg
1   212.i.jpg
2   512.i.jpg
3  1212.i.jpg

Keep original data index

df.loc[natsorted(df.index,key=lambda x : df.data[x] )]
Out[138]: 
         data
1   121.i.jpg
2   212.i.jpg
3   512.i.jpg
0  1212.i.jpg

Or using argsort with split

df.iloc[np.argsort(df.data.str.split('.').str[0].astype(int))]
Out[141]: 
         data
1   121.i.jpg
2   212.i.jpg
3   512.i.jpg
0  1212.i.jpg
BENY
  • 317,841
  • 20
  • 164
  • 234