Pandas pivot_table保留顺序

Rah*_*jan 3 python pivot-table dataframe pandas

>>> df
   A   B   C      D
0  foo one small  1
1  foo one large  2
2  foo one large  2
3  foo two small  3
4  foo two small  3
5  bar one large  4
6  bar one small  5
7  bar two small  6
8  bar two large  7
>>> table = pivot_table(df, values='D', index=['A', 'B'],
...                     columns=['C'], aggfunc=np.sum)
>>> table
          small  large
foo  one  1      4
     two  6      NaN
bar  one  5      4
     two  6      7
Run Code Online (Sandbox Code Playgroud)

我希望输出如上所示,但我得到一个排序输出.酒吧高于foo等等.

Eri*_*nil 12

pandas 1.3.0开始,可以sort=False在 中指定pd.pivot_table

>>> import pandas as pd
>>> 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]})
>>> pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'],
...                aggfunc='sum', sort=False)
C        large  small
A   B                
foo one    4.0    1.0
    two    NaN    6.0
bar one    4.0    5.0
    two    7.0    6.0
Run Code Online (Sandbox Code Playgroud)


ayh*_*han 7

我认为pivot_table没有排序选项,但是groupby有:

df.groupby(['A', 'B', 'C'], sort=False)['D'].sum().unstack('C')
Out: 
C        small  large
A   B                
foo one    1.0    4.0
    two    6.0    NaN
bar one    5.0    4.0
    two    6.0    7.0
Run Code Online (Sandbox Code Playgroud)

您将分组列传递给groupby,对于要显示为列值的那些,您可以使用unstack.

如果您不想要索引名称,请将它们重命名为None:

df.groupby(['A', 'B', 'C'], sort=False)['D'].sum().rename_axis([None, None, None]).unstack(level=2)
Out: 
         small  large
foo one    1.0    4.0
    two    6.0    NaN
bar one    5.0    4.0
    two    6.0    7.0
Run Code Online (Sandbox Code Playgroud)


stu*_*ent 3

创建时pivot_table,索引会自动 按字母顺序排序。不仅foobar,您可能还注意到smalllarge是排序的。如果您想foo位于顶部,您可能需要sort再次使用它们sortlevel。如果您期望输出如此处示例所示,则可能需要A对两者进行排序。C

table.sortlevel(["A","B"], ascending= [False,True], sort_remaining=False, inplace=True)
table.sortlevel(["C"], axis=1, ascending=False,  sort_remaining=False, inplace=True)
print(table)
Run Code Online (Sandbox Code Playgroud)

输出:

C        small  large
A   B                
foo one  1.0    4.0  
    two  6.0    NaN   
bar one  5.0    4.0  
    two  6.0    7.0  
Run Code Online (Sandbox Code Playgroud)

更新:

要删除索引名称A,BC:

table.columns.name = None
table.index.names = (None, None)
Run Code Online (Sandbox Code Playgroud)