[英]How to sort a pandas dataframe by a column that has both numbers and strings?
我有一個看起來像這樣的數據框
col0 col1 col2 col4
1 '1ZE7999' 865545 20 20
2 'R022428' 865584 297 0
3 34 865665 296 0
4 56 865700 297 0
5 100 865628 292 5
我想按'col0'對其進行排序,首先是數值,然后是字符串,Excel排序的方式
col0 col1 col2 col4
3 34 865665 296 0
4 56 865700 297 0
5 100 865628 292 5
1 '1ZE7999' 865545 20 20
2 'R022428' 865584 297 0
我用了
df.sort_values(by='col1', ascending=True)
但這不是這樣排序的,它從 0-9 排序,然后是 az
col0 col1 col2 col4
1 '1ZE7999' 865545 20 20
5 100 865628 292 5
3 34 865665 296 0
4 56 865700 297 0
2 'R022428' 865584 297 0
pd.to_numeric
+ sort_values
+ loc
-
df.loc[pd.to_numeric(df.col0, errors='coerce').sort_values().index]
col0 col1 col2 col4
3 34 865665 296 0
4 56 865700 297 0
5 100 865628 292 5
1 '1ZE7999' 865545 20 20
2 'R022428' 865584 297 0
細節
pd.to_numeric
脅迫非整數值,以NaN
-
i = pd.to_numeric(df.col0, errors='coerce')
i
1 NaN
2 NaN
3 34.0
4 56.0
5 100.0
Name: col0, dtype: float64
sort_values
對列進行排序,忽略NaN。
j = i.sort_values()
j
3 34.0
4 56.0
5 100.0
1 NaN
2 NaN
Name: col0, dtype: float64
觀察索引。 您需要做的就是使用索引來重新索引數據框。 loc
或reindex
都可以做到。
df.loc[j.index]
col0 col1 col2 col4
3 34 865665 296 0
4 56 865700 297 0
5 100 865628 292 5
1 '1ZE7999' 865545 20 20
2 'R022428' 865584 297 0
df.reindex(index=j.index)
col0 col1 col2 col4
3 34 865665 296 0
4 56 865700 297 0
5 100 865628 292 5
1 '1ZE7999' 865545 20 20
2 'R022428' 865584 297 0
如果您需要重置索引,這很容易做到。
df.loc[j.index].reset_index(drop=True)
col0 col1 col2 col4
0 34 865665 296 0
1 56 865700 297 0
2 100 865628 292 5
3 '1ZE7999' 865545 20 20
4 'R022428' 865584 297 0
通過使用natsort
from natsort import natsorted
df.set_index('col0').reindex(natsorted(df.col0.tolist(), key=lambda y: y.lower())).reset_index()
Out[736]:
col0 col1 col2 col4
0 34 865665 296 0
1 56 865700 297 0
2 100 865628 292 5
3 '1ZE7999' 865545 20 20
4 'R022428' 865584 297 0
使用index_humansorted
的natsort
import natsort
df = df.iloc[natsort.index_humansorted(df['col0'])]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.