[英]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.