簡體   English   中英

pandas value_counts:按值排序,然后按字母順序?

[英]pandas value_counts: sort by value, then alphabetically?

我有以下數據框:

df = pd.DataFrame({
    'fruit':
       ['peaches']*5 + ['apples']*5 + ['bananas']*3 + 
       ['nectarines']*3 + ['carrots']*3 + ['apricots'] 
})

我想先按值計數對輸出進行排序,然后按水果名稱的字母順序排序:

apples        5
peaches       5
bananas       3
carrots       3
nectarines    3
apricots      1

我找到了這個答案,但它看起來已經過時了。

似乎只使用value_counts會產生結果

df.fruit.value_counts()
Out[818]: 
apples        5
peaches       5
bananas       3
carrots       3
nectarines    3
apricots      1
Name: fruit, dtype: int64

更新

df.fruit.value_counts().sort_index(ascending=False).sort_values(ascending=False)    

apples        5
peaches       5
bananas       3
carrots       3
nectarines    3
apricots      1
Name: fruit, dtype: int64

您可以實現這一點,但輸出將是一個元組列表,按水果名稱和水果數量的字母順序排序。 首先將 value_counts() 輸出轉換為字典,然后使用 items 函數將其轉換為元組列表並對其進行排序:

sorted(dict(df.fruit.value_counts()).items())

注意:接受的答案有些混亂。 我建議使用此解決方案來確保它在不同版本之間確定性地運行。

你可以這樣做(如果你真的不關心細節):

df.fruit.value_counts().reset_index().sort_values(
    ['fruit', 'index'], ascending=[False, True]
)

輸出為數據幀:

        index  fruit
1      apples      5
0     peaches      5
2     bananas      3
4     carrots      3
3  nectarines      3
5    apricots      1

但如果你真的關心,那就是准確的答案:

df.fruit.value_counts().reset_index().sort_values(
    ['fruit', 'index'], ascending=[False, True]
).set_index('index').rename_axis(None)['fruit']

以完全相同的格式輸出:

apples        5
peaches       5
bananas       3
carrots       3
nectarines    3
apricots      1
Name: fruit, dtype: int64

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM