python - Make row value into column and sum for DataFrame -
maybe easy, can't figure out on own.
i have next dataframe:
date currency amount 0 2014-10-17 eur -20000000 1 2014-10-17 eur -80000000 2 2014-10-17 usd -20000000 3 2014-10-18 jpy -20000000 4 2014-10-19 usd -10000000 5 2014-10-19 usd -20000000 6 2014-10-20 jpy -20000000 7 2014-10-20 jpy -20000000
and want create currency tickers column names , @ same time, sum amounts each day, result like:
date eur usd jpy 0 2014-10-17 -100000000 -20000000 0.0 1 2014-10-18 0.0 0.0 -20000000 2 2014-10-19 0.0 -30000000 0.0 3 2014-10-20 0.0 0.0 -40000000
any clues?
either using .pivot_table
:
>>> df.pivot_table(index='date', columns='currency', ... values='amount', aggfunc='sum', fill_value=0) currency eur jpy usd date 2014-10-17 -100000000 0 -20000000 2014-10-18 0 -20000000 0 2014-10-19 0 0 -30000000 2014-10-20 0 -40000000 0
or, .groupby
followed .unstack
, followed .fillna
:
>>> df.groupby(['date', 'currency'])['amount'].agg('sum').unstack().fillna(0) currency eur jpy usd date 2014-10-17 -100000000 0 -20000000 2014-10-18 0 -20000000 0 2014-10-19 0 0 -30000000 2014-10-20 0 -40000000 0
python pandas
No comments:
Post a Comment