熊猫:添加交叉表总计
如何在交叉表中添加总计的另一行和一列?
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
我以为我会添加新列(通过对行求和而获得)
ct["Total"] = ct.0 + ct.1
但这不起作用。
-
这是因为“类似属性”的列访问不适用于整数列名。使用标准索引:
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
请参阅文档本节末尾的警告:http : //pandas.pydata.org/pandas-
docs/stable/indexing.html#attribute-access当您要使用行时,可以使用
.loc
:In [126]: ct.loc["Total"] = ct.loc[0] + ct.loc[1]
在这种情况下
ct.loc["Total"]
相当于ct.loc["Total", :]