熊猫Pivot_table

时间:2020-07-07 16:31:36

标签: python pandas

我正在尝试创建一个数据透视表,该数据透视表的每一行都列出了索引。目前,我只在第一次出现它们。

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

我希望 foobar分别出现在第二行和第四行,以便所有行都有一个值。

2 个答案:

答案 0 :(得分:3)

此内容记录在docs中 : enter image description here

因此您可以这样做:

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

答案 1 :(得分:2)

这是MultiIndex数据显示机制的副产品。 使用table.reset_index()将索引移回各列,您将看到所有列都显示有所有值。