获取 pandas 数据框中所有唯一行的计数 [英] Get count of all unique rows in pandas dataframe

查看:78
本文介绍了获取 pandas 数据框中所有唯一行的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫DataFrame-

I have a Pandas DataFrame -

>>> import numpy as np
>>> import pandas as pd
>>> data = pd.DataFrame(np.random.randint(low=0, high=2,size=(5,3)),
...                       columns=['A', 'B', 'C'])
>>> data
   A  B  C
0  0  1  0
1  1  0  1
2  1  0  1
3  0  1  1
4  1  1  0

现在我用它来获取仅A列的行数

Now I use this to get the count of rows only for column A

>>> data.ix[:, 'A'].value_counts()
1    3
0    2
dtype: int64

获取列A和列B的行数的最有效方法是什么,即类似于以下输出-

What is the most efficient way to get the count of rows for column A and B i.e something like the following output -

0    0    0
0    1    2
1    0    2
1    1    1

然后最后如何将其转换为numpy数组,例如-

And then finally how can I convert it into a numpy array such as -

array([[0, 2],
       [2, 1]])

请提供与

>>>> data = pd.DataFrame(np.random.randint(low=0, high=2,size=(5,2)),
...                       columns=['A', 'B'])

推荐答案

您可以使用groupby 取消堆叠:

You can use groupby size and then unstack:

In [11]: data.groupby(["A","B"]).size()
Out[11]:
A  B
0  1    2
1  0    2
   1    1
dtype: int64

In [12]: data.groupby(["A","B"]).size().unstack("B")
Out[12]:
B   0  1
A
0 NaN  2
1   2  1

In [13]: data.groupby(["A","B"]).size().unstack("B").fillna(0)
Out[13]:
B  0  1
A
0  0  2
1  2  1

但是,每当您进行分组并随后进行堆叠时,您都应该考虑:

However whenever you do a groupby followed by an unstack you should think: pivot_table:

In [21]: data.pivot_table(index="A", columns="B", aggfunc="count", fill_value=0)
Out[21]:
   C
B  0  1
A
0  0  2
1  2  1

这将是最有效的解决方案,也是最直接的解决方案.

这篇关于获取 pandas 数据框中所有唯一行的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆