Python 在 Pandas value_counts() 中提取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35523635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:33:05  来源:igfitidea点击:

Extract values in Pandas value_counts()

pythonpandasdataframeseries

提问by JamesButterlips

Say we have used pandas dataframe[column].value_counts()which outputs:

假设我们使用了dataframe[column].value_counts()输出:

 apple   5 
 sausage 2
 banana  2
 cheese  1

How do you extract the values in the order same as shown above from max to min ?

您如何按照与上述相同的顺序从 max 到 min 提取值?

e.g: [apple,sausage,banana,cheese]

例如: [apple,sausage,banana,cheese]

采纳答案by Mike Müller

Try this:

尝试这个:

dataframe[column].value_counts().index.tolist()
['apple', 'sausage', 'banana', 'cheese']

回答by Joe T. Boka

First you have to sortthe dataframeby the countcolumn maxto minif it's not sorted that way already. In your post, it is in the right order already but I will sortit anyways:

首先,你必须sortdataframecountmaxmin,如果没有排序已经如此。在您的帖子中,它的顺序已经正确,但sort无论如何我都会这样做:

dataframe.sort_index(by='count', ascending=[False])
    col     count
0   apple   5
1   sausage 2
2   banana  2
3   cheese  1 

Then you can output the colcolumn to a list:

然后您可以将col列输出到列表:

dataframe['col'].tolist()
['apple', 'sausage', 'banana', 'cheese']

回答by Martin Thoma

#!/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()

Now, print(df['country'].value_counts())gives:

现在,print(df['country'].value_counts())给出:

France       3
Germany      2
UK           1
Indonesia    1

and print(values)gives:

print(values)给出:

['France', 'Germany', 'UK', 'Indonesia']

and print(counts)gives:

print(counts)给出:

[3, 2, 1, 1]

回答by Sawant

If anyone missed it out in the comments, try this:

如果有人在评论中错过了它,请尝试以下操作:

dataframe[column].value_counts().to_frame()

回答by Harish Kumawat

Code

代码

train["label_Name"].value_counts()

where : label_Name Mean column_name

其中: label_Name 均值 column_name

result (my case) :-

结果(我的情况):-

0    29720 
1     2242 
Name: label, dtype: int64