如何向交叉表添加額外的行和總計的附加列?熊貓:添加交叉表合計
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
添加新列(由求和行獲得的),但這不起作用。
如何向交叉表添加額外的行和總計的附加列?熊貓:添加交叉表合計
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", :]
實際上pandas.crosstab
已經p提供一個選項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
基本上,通過設置margins=True
,所得到的頻數分佈表將增加一個「全部」列與「全部」行該計算小計。
您應該使用margins = True和crosstab。這應該做的工作!
哦完美的謝謝。那另外一排呢?有沒有類似的方法? – meto 2014-11-14 15:34:27
查看更新的答案 – joris 2014-11-14 15:37:18