2017-02-28 5 views
3

이름 길이로 정렬하고 싶습니다. sort_values에 대해 key 매개 변수가 나타나지 않으므로이를 수행하는 방법을 잘 모르겠습니다.문자열 길이로 데이터 프레임 정렬

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

당신은 sort_valueslen 만든 Seriesindexreindex를 사용할 수 있습니다 : 여기에 테스트 DF이다

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 
문자열의 길이에 의해 [정렬 dataframe의
+0

좋은 대답은,'.str.len()'이 질문에 언급 된 목록과 함께 작동하기 때문에 목록을 가지고이 접근법을 시도한 것입니다. (목록 길이로 DataFrame 정렬하기) ** 팬더 데이터 프레임 열의리스트의 길이를 계산하는 Pythonic 방법 **이 [link] (https://stackoverflow.com/questions/41340341/pythonic-way-for-calculating-length-of-lists-in-pandas-dataframe-column) – otayeby