如何在交叉表中添加一个额外的行和一个额外的列?
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
Run Code Online (Sandbox Code Playgroud)
我以为我会添加新列(通过对行进行求和得到)
ct["Total"] = ct.0 + ct.1
Run Code Online (Sandbox Code Playgroud)
但这不起作用.
Ida*_*Ida 21
实际上pandas.crosstab
已经提供了一个选项margins
,它可以完全满足您的需求.
> 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
Run Code Online (Sandbox Code Playgroud)
基本上,通过设置margins=True
,生成的频率表将添加"全部"列和计算小计的"全部"行.
这是因为“类似属性”的列访问不适用于整数列名称。使用标准索引:
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
Run Code Online (Sandbox Code Playgroud)
请参阅文档中本节末尾的警告:http://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access
当您想要处理行时,可以使用.loc
:
In [126]: ct.loc["Total"] = ct.loc[0] + ct.loc[1]
Run Code Online (Sandbox Code Playgroud)
在这种情况下ct.loc["Total"]
相当于ct.loc["Total", :]