简体   繁体   English

Excel行的升序

[英]Ascending order of Excel rows

I have the following rows in Excel: 我在Excel中有以下行:

在此处输入图片说明

How can I put them in an ascending order in Python (ie notice how the row starting with 12 comes before that starting with 118). 如何在Python按升序排列它们(即注意以12开头的行在以118开头的行之前是如何出现的)。

I think the Pandas library would be a starting point? 我认为熊猫图书馆将是一个起点? Any clue is appreciated. 任何线索表示赞赏。

Thanks. 谢谢。

First read the excel file 首先阅读excel文件

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 以防万一,将新列转换为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

Using natsorted 使用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 或者将argsortsplit argsort使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM