Python 熊猫:添加交叉表总计
如何向交叉表中添加总计的附加行和附加列Python 熊猫:添加交叉表总计,python,pandas,Python,Pandas,如何向交叉表中添加总计的附加行和附加列 df = pd.DataFrame({"A": np.random.randint(0,2,100), "B" : np.random.randint(0,2,100)}) ct = pd.crosstab(new.A, new.B) ct 我想我会将新列(通过对行求和获得)添加到 但这不起作用。这是因为“类属性”列访问不适用于整数列名。使用标准索引: In [122]: ct["Total"] = ct[0] + ct[1] In [123]: c
df = pd.DataFrame({"A": np.random.randint(0,2,100), "B" : np.random.randint(0,2,100)})
ct = pd.crosstab(new.A, new.B)
ct
我想我会将新列(通过对行求和获得)添加到
但这不起作用。这是因为“类属性”列访问不适用于整数列名。使用标准索引:
In [122]: ct["Total"] = ct[0] + ct[1]
In [123]: ct
Out[123]:
B 0 1 Total
A
0 26 24 50
1 30 20 50
请参阅文档中本节末尾的警告:
要处理行时,可以使用.loc
:
In [126]: ct.loc["Total"] = ct.loc[0] + ct.loc[1]
在这种情况下,
ct.loc[“Total”]
相当于ct.loc[“Total”,:]
事实上,pandas。交叉表已经提供了一个选项边距
,这正是您想要的
> df = pd.DataFrame({"A": np.random.randint(0,2,100), "B" : np.random.randint(0,2,100)})
> pd.crosstab(df.A, df.B, margins=True)
B 0 1 All
A
0 26 21 47
1 25 28 53
All 51 49 100
基本上,通过设置margins=True
,生成的频率表将添加一个“All”列和一个计算小计的“All”行。您应该将margins=True与交叉表一起使用。那应该可以了 哦,太好了,谢谢。那另一排呢?有类似的方法吗?
> df = pd.DataFrame({"A": np.random.randint(0,2,100), "B" : np.random.randint(0,2,100)})
> pd.crosstab(df.A, df.B, margins=True)
B 0 1 All
A
0 26 21 47
1 25 28 53
All 51 49 100