简体   繁体   English

如何在熊猫字符串中对数字进行排序?

[英]How can I sort numbers in a string in pandas?

I have a dataframe like this: 我有一个这样的数据框:

id   String
1    345 -456 -13  879
2    158 -926 -81  249 35 -4 -53  9
3    945 -506 -103

I want to sort it in desending order like this 我想按这样的降序排序

id   String
1    879 345 -13 -457
2    249 158 35 9 -4 -53 -81 -926
3    945 -103 -506

I tried this: 我尝试了这个:

df['string'] = df['string'].str.split(' ').map(lambda x: ' '.join(sorted(x)))

The above function do some kind of sorting but not the way I want it. 上面的函数进行某种排序,但不是我想要的方式。

First is necessary convert values to integers, sorting and then convert to strings back: 首先需要将值转换为整数,进行排序,然后再转换回字符串:

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

Or: 要么:

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.

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