[英]Pandas pivot_table
我正在嘗試創建一個 pivot 表,該表在每一行中都列出了索引。 目前,我只讓它們出現在第一個實例中。
df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
"bar", "bar", "bar", "bar"],
"B": ["one", "one", "one", "two", "two",
"one", "one", "two", "two"],
"C": ["small", "large", "large", "small",
"small", "large", "small", "small",
"large"],
"D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
"E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
df
A B C D E
0 foo one small 1 2
1 foo one large 2 4
2 foo one large 2 5
3 foo two small 3 5
4 foo two small 3 6
5 bar one large 4 6
6 bar one small 5 8
7 bar two small 6 9
8 bar two large 7 9
table = pd.pivot_table(df, values='D', index=['A', 'B'],
columns=['C'], aggfunc=np.sum)
table
C large small
A B
bar one 4.0 5.0
two 7.0 6.0
foo one 4.0 1.0
two NaN 6.0
我希望foo
和bar
分別出現在第 2 行和第 4 行,以便所有行都有一個值。
這記錄在文檔中:
所以你可以這樣做:
with pd.option_context('display.multi_sparse', False):
print(table)
C large small
A B
bar one 4.0 5.0
bar two 7.0 6.0
foo one 4.0 1.0
foo two NaN 6.0
這是MultiIndex
數據顯示機制的副產品。 使用table.reset_index()
將索引移回列中,您將看到所有列都顯示為所有值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.