Learn Before
Concept

Pivot Tables

Pandas pivot table usage is built for the pivoting of aggregate numerical data. Given the following data frame

A B C D E F 0 one A foo 0.341734 -0.317441 2013-01-01 1 one B foo 0.959726 -1.236269 2013-02-01 2 two C foo -1.110336 0.896171 2013-03-01 3 three A bar -0.619976 -0.487602 2013-04-01 4 one B bar 0.149748 -0.082240 2013-05-01 .. ... .. ... ... ... ... 19 three B foo 0.690579 -2.213588 2013-08-15 20 one C foo 0.995761 1.063327 2013-09-15 21 one A bar 2.396780 1.266143 2013-10-15 22 two B bar 0.014871 0.299368 2013-11-15 23 three C bar 3.357427 -0.863838 2013-12-15 [24 rows x 6 columns]

We can pivot it to display the data in column D with index information from columns A and B and column separation using column C with pd.pivot_table(df, values="D", index=["A", "B"], columns=["C"]).

This will generate the following table.

C bar foo A B one A 1.120915 -0.514058 B -0.338421 0.002759 C -0.538846 0.699535 three A -1.181568 NaN B NaN 0.433512 C 0.588783 NaN two A NaN 1.000985 B 0.158248 NaN C NaN 0.176180

Aggregate functions can also be used. pd.pivot_table(df, values="D", index=["B"], columns=["A", "C"], aggfunc=np.sum) would produce :

A one three two C bar foo bar foo bar foo B A 2.241830 -1.028115 -2.363137 NaN NaN 2.001971 B -0.676843 0.005518 NaN 0.867024 0.316495 NaN C -1.077692 1.399070 1.177566 NaN NaN 0.352360

0

1

Updated 2021-06-02

Tags

Python Programming Language

Data Science

Related