在Pandas中,有没有Python的方法可以用来制作列联表? [英] Is there a pythonic way to do a contingency table in Pandas?

查看:276
本文介绍了在Pandas中,有没有Python的方法可以用来制作列联表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个看起来像这样的数据框:

Given a dataframe that looks like this:

            A   B      
2005-09-06  5  -2  
2005-09-07 -1   3  
2005-09-08  4   5 
2005-09-09 -8   2
2005-09-10 -2  -5
2005-09-11 -7   9 
2005-09-12  2   8  
2005-09-13  6  -5  
2005-09-14  6  -5  

是否有Python方式创建这样的2x2矩阵:

Is there a pythonic way to create a 2x2 matrix like this:

    1  0
 1  a  b
 0  c  d

位置:

a = ob数,其中A列和B列的对应元素均为正.

a = number of obs where the corresponding elements of column A and B are both positive.

b = ob数,其中A列的相应元素在B列中为正和负.

b = number of obs where the corresponding elements of column A are positive and negative in column B.

c = ob数,其中A列的相应元素在B列中为负数和正数.

c = number of obs where the corresponding elements of column A are negative and positive in column B.

d = Obs的数量,其中A列和B列的对应元素均为负.

d = number of obs where the corresponding elements of column A and B are both negative.

在此示例中,输出为:

    1  0
 1  2  3
 0  3  1

谢谢

推荐答案

让我们将您的数据框称为data.试试

Let us call your dataframe data. Try

a = data['A']>0
b = data['B']>0
data.groupby([a,b]).count() 

这篇关于在Pandas中,有没有Python的方法可以用来制作列联表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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