Python 3.x 如何获取数据帧中第一个和最后一个值的百分比变化
我想知道如何从以下数据帧的第一个和最后一个值的列平衡、导出和导入中获取pct_变化?如果你能举例说明如何从两个特定日期获得pct_变更,那也很好Python 3.x 如何获取数据帧中第一个和最后一个值的百分比变化,python-3.x,pandas,Python 3.x,Pandas,我想知道如何从以下数据帧的第一个和最后一个值的列平衡、导出和导入中获取pct_变化?如果你能举例说明如何从两个特定日期获得pct_变更,那也很好 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-0
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
IIUIC,对于第一个
.iloc[0]
和最后一个.iloc[-1]
使用iloc
,以获得pct\u更改100*(最后一个/first-1)
IIUIC,对于第一个
.iloc[0]
和最后一个.iloc[-1]
使用iloc
,以获得pct\u更改100*(最后一个/first-1)
首先,如果要直接使用日期,必须将索引设置为date。然后一切都很容易
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
首先,如果要直接使用日期,必须将索引设置为date。然后一切都很容易
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