[英]How can I sort numbers in a string in pandas?
我有一個這樣的數據框:
id String
1 345 -456 -13 879
2 158 -926 -81 249 35 -4 -53 9
3 945 -506 -103
我想按這樣的降序排序
id String
1 879 345 -13 -457
2 249 158 35 9 -4 -53 -81 -926
3 945 -103 -506
我嘗試了這個:
df['string'] = df['string'].str.split(' ').map(lambda x: ' '.join(sorted(x)))
上面的函數進行某種排序,但不是我想要的方式。
首先需要將值轉換為整數,進行排序,然后再轉換回字符串:
f = lambda x: ' '.join(map(str, sorted(map(int, x), reverse=True)))
#another solution
#f = lambda x: ' '.join(str(z) for z in sorted((int(y) for y in x), reverse=True))
df['string'] = df['string'].str.split().map(f)
print (df)
id string
0 1 879 345 -13 -456
1 2 249 158 35 9 -4 -53 -81 -926
2 3 945 -103 -506
要么:
f = lambda x: ' '.join(map(str, sorted(map(int, x.split()), reverse=True)))
df['string'] = df['string'].map(f)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.