If I have a multiindex DataFrame in Pandas, if I read through the documentation of pivot
and pivot_table
I cannot seem to find the reason why pivot
doesn't work in this example. Clearly I am missing something, but it takes the same parameters and seems to suggest that it would work. What am I missing here? Why does pivot
throw an error but pivot_table
works perfectly. Thanks.
# standard imports
import pandas as pd
# create a random multiindex dataframe
outside = ['G1','G1','G1','G2','G2','G2']
inside = [1,2,3,1,2,3]
hier_index = list(zip(outside,inside))
hier_index = pd.MultiIndex.from_tuples(hier_index)
df = pd.DataFrame(np.random.randn(6,1),index=hier_index,columns=['A'])
df.index.names = ['Group', 'Num']
# show the original dataframe
print(df)
# successfully pivots the dataframe as requested
print(df.pivot_table(index='Group', columns='Num', values='A'))
# causes a KeyError on 'Group' - not understanding why
print(df.pivot(index='Group', columns='Num', values='A'))
Here function pivot
not working with MultiIndex
, solution is DataFrame.reset_index
for convert levels to columns:
print(df.reset_index().pivot(index='Group', columns='Num', values='A'))
Num 1 2 3
Group
G1 -0.121167 -2.008585 -0.920647
G2 0.168234 -1.319892 1.266429
I think reason why working pivot_table
nice is hidden in groupby-enhancements
- you can use groupby
by levels and similar pivot_table
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.