Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

DataFrame.pivot vs pandas.pivot_table

  1. Both DataFrame.pivot and pandas.pivot_table can generate pivot tables. pandas.pivot_table aggregate values while DataFrame.pivot not.

import pandas as pd
import numpy as np

df = pd.DataFrame(
    {"id": ["a", "b", "c"], "x": [1, 3, 5], "y": [2, 4, 6], "z": [7, 8, 9]}
)
df
Loading...
dfm = pd.melt(df, id_vars="id", value_vars=["x", "y", "z"])
dfm
Loading...

DataFrame.pivot

The values option is not flexible at this time. It accepts a column name or None but cannot accept a list of columns at this time. One way to achieve it is to specify None for values and then select columns you want manually.

dfp = dfm.pivot(index="id", columns="variable", values="value")
dfp
Loading...
dfp.index
Index(['a', 'b', 'c'], dtype='object', name='id')
 unstack pivot_table, ...
jj = j.unstack()

pandas.pivot_table

pd.pivot_table(dfm, index="id", columns="variable", values="value")
Loading...
df = pd.DataFrame(
    data=[
        ["foo", "one", "small", 1],
        ["foo", "one", "large", 2],
        ["foo", "one", "large", 2],
        ["foo", "two", "small", 3],
        ["foo", "two", "small", 3],
        ["bar", "one", "large", 4],
        ["bar", "one", "small", 5],
        ["bar", "two", "small", 6],
        ["bar", "two", "large", 7],
    ],
    columns=["a", "b", "c", "d"],
)
df
Loading...
pd.pivot_table(df, index=["a", "b"], columns="c", values="d", aggfunc=np.sum)
Loading...