[英]Extract values in Pandas value_counts()
假設我們使用了dataframe[column].value_counts()
輸出:
apple 5
sausage 2
banana 2
cheese 1
您如何按照與上述相同的順序從 max 到 min 提取值?
例如: [apple,sausage,banana,cheese]
嘗試這個:
dataframe[column].value_counts().index.tolist()
['apple', 'sausage', 'banana', 'cheese']
#!/usr/bin/env python
import pandas as pd
# Make example dataframe
df = pd.DataFrame([(1, 'Germany'),
(2, 'France'),
(3, 'Indonesia'),
(4, 'France'),
(5, 'France'),
(6, 'Germany'),
(7, 'UK'),
],
columns=['groupid', 'country'],
index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
# What you're looking for
values = df['country'].value_counts().keys().tolist()
counts = df['country'].value_counts().tolist()
現在, print(df['country'].value_counts())
給出:
France 3
Germany 2
UK 1
Indonesia 1
和print(values)
給出:
['France', 'Germany', 'UK', 'Indonesia']
和print(counts)
給出:
[3, 2, 1, 1]
如果有人在評論中錯過了它,請嘗試以下操作:
dataframe[column].value_counts().to_frame()
提取值的最佳方法是執行以下操作
json.loads(dataframe[column].value_counts().to_json())
這將返回一個字典,您可以像使用任何其他字典一樣使用它。 使用值或鍵。
{"apple": 5, "sausage": 2, "banana": 2, "cheese": 1}
首先你要sort
的dataframe
由count
列max
到min
,如果沒有排序已經如此。 在您的帖子中,它的順序已經正確,但無論如何我都會對其進行sort
:
dataframe.sort_index(by='count', ascending=[False])
col count
0 apple 5
1 sausage 2
2 banana 2
3 cheese 1
然后您可以將col
列輸出到列表:
dataframe['col'].tolist()
['apple', 'sausage', 'banana', 'cheese']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.