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¶
Both
DataFrame.pivotandpandas.pivot_tablecan generate pivot tables.pandas.pivot_tableaggregate values whileDataFrame.pivotnot.
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]}
)
dfLoading...
dfm = pd.melt(df, id_vars="id", value_vars=["x", "y", "z"])
dfmLoading...
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")
dfpLoading...
dfp.indexIndex(['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"],
)
dfLoading...
pd.pivot_table(df, index=["a", "b"], columns="c", values="d", aggfunc=np.sum)Loading...