在Pandas中提取值value_counts()

时间:2016-02-20 13:03:08

标签: python pandas dataframe series

假设我们使用过熊猫' dataframe[column].value_counts()输出:

 apple   5 
 sausage 2
 banana  2
 cheese  1

如何按上面显示的顺序从中提取值,例如最大到分钟? [apple,sausage,banana,cheese]

6 个答案:

答案 0 :(得分:65)

试试这个:

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

答案 1 :(得分:21)

#!/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]

答案 2 :(得分:12)

如果有人在评论中遗漏了它,请尝试:

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

答案 3 :(得分:2)

提取值的最佳方法是执行以下操作

json.loads(dataframe[column].value_counts().to_json())

这将返回一个字典,您可以像其他字典一样使用它。使用值或键。

 {"apple": 5, "sausage": 2, "banana": 2, "cheese": 1}

答案 4 :(得分:1)

首先,sortdataframe 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']

然后您可以将preg_match_all('/(\b\p{Lu}\p{L}+\s*)+/u', $input, $output);列输出到列表:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

答案 5 :(得分:-1)

代码

train["label_Name"].value_counts().to_frame()

其中:label_Name表示列名

结果(我的情况):-

0    29720 
1     2242 
Name: label, dtype: int64