2017-02-28 84 views
3

我想按名稱長度排序。 sort_values似乎沒有key參數,所以我不確定如何完成此操作。下面是測試DF:按字符串長度對數據框排序

import pandas as pd 
df = pd.DataFrame({'name': ['Steve', 'Al', 'Markus', 'Greg'], 'score': [2, 4, 2, 3]}) 
+0

可能的複製一個列](https://stackoverflow.com/questions/46177362/sort-dataframe-by-length-of-string-in-a-column) –

+0

@jezrael請閱讀我的理由。我明確提到它:https://stackoverflow.com/questions/46177362/sort-dataframe-by-length-of-string-in-a-column#comment79318016_46177362 –

+0

那裏有更多的選項。如果沒有,你可以編輯這個答案幷包含所有其他解決方案。 –

回答

7

您可以使用由len創建Seriesindexreindexsort_values

print (df.name.str.len()) 
0 5 
1 2 
2 6 
3 4 
Name: name, dtype: int64 

print (df.name.str.len().sort_values()) 
1 2 
3 4 
0 5 
2 6 
Name: name, dtype: int64 

s = df.name.str.len().sort_values().index 
print (s) 
Int64Index([1, 3, 0, 2], dtype='int64') 

print (df.reindex(s)) 
    name score 
1  Al  4 
3 Greg  3 
0 Steve  2 
2 Markus  2 

df1 = df.reindex(s) 
df1 = df1.reset_index(drop=True) 
print (df1) 
    name score 
0  Al  4 
1 Greg  3 
2 Steve  2 
3 Markus  2 
在字符串的長度[排序數據幀的
+0

偉大的答案,我也嘗試過這種方法列表(按列表長度排序DataFrame),因爲'.str.len()'與問題中提到的列表一起工作**用於計算pandas數據框列表中列表長度的Pythonic方法**在這[鏈接](https://stackoverflow.com/questions/41340341/pythonic-way-for-calculating-length-of-lists-in-pandas-dataframe-column) – otayeby