我有一个这样的DataFrame:
>>> df = pd.DataFrame({'id_police':['s123','s124','s125','s126','s127'],
'raison':['dog','cat','cow','dog, cat, cow','dog, cat'],
})
>>> df
id_police raison
0 s123 dog
1 s124 cat
2 s125 cow
3 s126 dog, cat, cow
4 s127 dog, cat
我想按这样的DESC方式按列raison
排序(并且ID被重置,但id_police被保留):
id_police raison
0 s126 dog, cat, cow
1 s127 dog, cat
2 s123 dog
3 s124 cat
4 s125 cow
请帮助,我想我需要一个lambda
函数...
答案 0 :(得分:4)
您可以使用count
+ argsort
df.iloc[(-df.raison.str.count(',')).argsort()]
Out[12]:
id_police raison
3 s126 dog, cat, cow
4 s127 dog, cat
0 s123 dog
1 s124 cat
2 s125 cow
答案 1 :(得分:0)
为此,您可以使用sort_values
,然后再为,
创建一个计数列:
df['count'] = df.raison.str.count(',')
df = df.sort_values('count', ascending=False).reset_index(drop=True)
df = df.drop('count', axis=1)
print(df)
id_police raison
0 s126 dog, cat, cow
1 s127 dog, cat
2 s123 dog
3 s124 cat
4 s125 cow