python - How do I reshape or pivot a DataFrame in Pandas -
python - How do I reshape or pivot a DataFrame in Pandas -
i reshape dataframe in pandas not sure how go it. here's i'm starting with:
phase weight value cf aa heavy 0.28 1.0 ab lite 3.26 1.0 bx med 0.77 1.0 xy x lite -0.01 1.0 aa heavy 0.49 1.5 ab lite 5.10 1.5 bx med 2.16 1.5 xy x lite 0.98 1.5 aa heavy 2.48 2.0 ab lite 11.70 2.0 bx med 5.81 2.0 xy x lite 3.46 2.0
i reshape this:
phase weight 1.0 1.5 2.0 aa heavy 0.28 0.49 2.48 ab lite 3.26 5.10 11.70 bx med 0.77 2.16 5.81 xy x lite -0.01 0.98 3.46
so column names values in cf , intersection of row , columns in new table values in value column in original table.
i know can phase column index so:
df.pivot(index='phase', columns='cf', values='value)
but miss weight column.i tried i'm getting error
df.pivot(index='phase', columns=['weight','cf'], values='value')
is there way single statement ? if not, best way ?
you can pd.pivot_table
can take multiple names arguments index/column parameters. think want weight on index (which makes column in output) rather on columns (which turns distinct values columns).
in [27]: df.pivot_table(index=['phase','weight'], columns='cf', values='value').reset_index() out[27]: cf phase weight 1.0 1.5 2.0 0 aa heavy 0.28 0.49 2.48 1 ab lite 3.26 5.10 11.70 2 bx med 0.77 2.16 5.81 3 xy x lite -0.01 0.98 3.46
edit:
on other question, .columns
of dataframe index (just on rows), , have .name
in add-on actual values. far i'm aware, it's used display purposes.
in [74]: df.columns out[74]: index([u'phase', u'weight', 1.0, 1.5, 2.0], dtype='object') in [75]: df.columns.name out[75]: 'cf' in [76]: df.columns.values out[76]: array(['phase', 'weight', 1.0, 1.5, 2.0], dtype=object)
python pandas
Comments
Post a Comment