I want to reshape my dataframe so I can pivot the 'kind' field, but I also want to include per-row aggregations.
df = pd.DataFrame([
{
'date': '2022-04-20',
'kind': 'alpha',
'scalar_a': 2,
'scalar_b': 5
},
{
'date': '2022-04-20',
'kind': 'bravo',
'scalar_a': 3,
'scalar_b': 7
},
{
'date': '2022-04-21',
'kind': 'charlie',
'scalar_a': 4,
'scalar_b': 3
},
{
'date': '2022-04-22',
'kind': 'bravo',
'scalar_a': 5,
'scalar_b': 1
},
])
I want to:
- Aggregate my data by date, and have it reshaped so I can see each kind side-by-side.
- I want to compare Scalar_A and Scalar_B from each kinds on the same row, including a per-kind aggregation.
- I want to also have a totals column (per-row/ per-date)
My attempt was to create two dataframes (one for calculating the per-date totals, and another one to perform the pivot transformation), and then concatenate them across the horizontal axis.
totals_df = df.groupby('date').agg(
total_a=('scalar_a', 'sum'),
total_b=('scalar_b', 'sum'),
)
# I also need a column calculated by the aggregated fields.
totals_df["Total a*b"] = totals_df["total_a"] * totals_df["total_b"]
# Then I sort by descending date.
totals_df = totals_df.sort_values('date',ascending=False)
# And then to build my pivoted dataframe
pivot_df = df.pivot_table(
index=['date'],
columns=['kind'],
fill_value=0
)
# I attempt to invert the two top-level headers ([scalar_a, scalar_b] with [])
pivot_fundos = pivot_fundos.swaplevel(1,0, axis=1).sort_index(axis=1)
How would I proceed to include a per-date/per-kind aggregation? I want to include a column with scalar_a + scalar_b for each kind sub-column.

Then I concatenate both dataframes.
concatenated_dataframes = pd.concat([pivot_df, totals_df], axis=1)
The resulting dataframe doesn't have the "two-levels" headers I expected when calling the to_table() method. How do I fix that?




