pandas :添加交叉表总计 [英] Pandas: add crosstab totals
问题描述
如何向交叉表中添加总计的另一行和另一列?
How can I add to my crosstab an additional row and an additional column for the totals?
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
我以为我会添加新列(通过对行进行求和而获得)
I thought I would add the new column (obtained by summing over the rows) by
ct["Total"] = ct.0 + ct.1
但这不起作用.
推荐答案
这是因为类似属性"的列访问不适用于整数列名.使用标准索引:
This is because 'attribute-like' column access does not work with integer column names. Using the standard indexing:
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
See the warnings at the end of this section in the docs: http://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access
要处理行时,可以使用.loc
:
When you want to work with the rows, you can use .loc
:
In [126]: ct.loc["Total"] = ct.loc[0] + ct.loc[1]
在这种情况下,ct.loc["Total"]
等效于ct.loc["Total", :]
In this case ct.loc["Total"]
is equivalent to ct.loc["Total", :]
这篇关于 pandas :添加交叉表总计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!