Reputation: 187
I would like to know how to obtain the pct_change from either column balance, exports and imports, from the first and last value of the following DataFrame? Also it would be nice if you could illustrate how to get the pct_change from two specific dates
balance date exports imports
0 -45053 2008-01-01 421443 466496
1 -33453 2009-01-01 399649 433102
2 -41168 2010-01-01 445748 486916
3 -25171 2011-01-01 498862 524033
4 -33364 2012-01-01 501055 534419
5 -35367 2013-01-01 519913 555280
6 -36831 2014-01-01 518925 555756
7 -32370 2015-01-01 517161 549531
8 -43013 2016-01-01 547473 590486
Upvotes: 0
Views: 2553
Reputation: 7211
First, you have to set your index as date if you want to use directly the dates. Then everything goes easily.
import pandas as pd
data = [[-45053, "2008-01-01", 421443, 466496],
[-33453, "2009-01-01", 399649, 433102],
[-41168, "2010-01-01", 445748, 486916],
[-25171, "2011-01-01", 498862, 524033],
[-33364, "2012-01-01", 501055, 534419],
[-35367, "2013-01-01", 519913, 555280],
[-36831, "2014-01-01", 518925, 555756],
[-32370, "2015-01-01", 517161, 549531],
[-43013, "2016-01-01", 547473, 590486]]
columns = ["balance","date","exports","imports"]
df=pd.DataFrame(data,columns=columns).set_index("date")
print(df.loc["2009-01-01"]/df.loc["2008-01-01"]-1)
# result
# balance -0.257475
# exports -0.051713
# imports -0.071585
# dtype: float64
Upvotes: 2
Reputation: 76937
IIUIC, use iloc
for first .iloc[0]
and last .iloc[-1]
to get pct_change 100*(last/first-1)
In [244]: cols = ['balance', 'exports', 'imports']
In [245]: 100*(df[cols].iloc[-1]/df[cols].iloc[0]-1)
Out[245]:
balance -4.528000
exports 29.904400
imports 26.579006
dtype: float64
Upvotes: 4