Python 以年增长率生成未来数据帧
当我有基准年和增长率的数据时,我试图为某个产品生成年度数据 在玩具的例子中,每种产品的“颜色”都有不同的年度效率增长率,我想生成2030年之前的年度数据 因此,我有如下基准年数据(基准年):Python 以年增长率生成未来数据帧,python,pandas,dataframe,Python,Pandas,Dataframe,当我有基准年和增长率的数据时,我试图为某个产品生成年度数据 在玩具的例子中,每种产品的“颜色”都有不同的年度效率增长率,我想生成2030年之前的年度数据 因此,我有如下基准年数据(基准年): year color shape efficiency 0 2018 red circle 50 1 2018 red square 30 2 2018 blue circle 100 3 2018 blue
year color shape efficiency
0 2018 red circle 50
1 2018 red square 30
2 2018 blue circle 100
3 2018 blue square 60
每种产品的增长率(增长率)如下:
我希望的结果是:
year color shape efficiency
0 2018 red circle 50
1 2018 red square 30
2 2018 blue circle 100
3 2018 blue square 60
4 2019 red circle 65
5 2019 red square 39
6 2019 blue circle 120
7 2019 blue square 72
8 2020 red circle 84.5
... (until 2030)
玩具代码中使用的数据为
base_year = pd.DataFrame(data = {'year': [2018,2018,2018,2018],
'color': ['red', 'red', 'blue', 'blue'],
'shape' : ['circle', 'square', 'circle', 'square'],
'efficiency' : [50, 30, 100, 60]}, columns = ['year', 'color', 'shape', 'efficiency'])
growthrate = pd.DataFrame(data = {'color': ['red', 'blue'],
'rate' : [30, 20]}, columns = ['color', 'rate'])
我一直在尝试一些使用.loc的方法,但这种方法似乎效率很低
如有任何建议或提示,将不胜感激。提前谢谢你 有一种方法可以做到这一点:
years = 2031 - 2018
df = (pd.concat([df.assign(year=df['year']+i,
efficiency=df['efficiency']*((df['rate']/100+1)**i))
for i, df in enumerate([base_year.merge(growthrate, on='color')] * years)])
.drop('rate', axis=1))
谢谢你的回答!高效优雅的方式!
years = 2031 - 2018
df = (pd.concat([df.assign(year=df['year']+i,
efficiency=df['efficiency']*((df['rate']/100+1)**i))
for i, df in enumerate([base_year.merge(growthrate, on='color')] * years)])
.drop('rate', axis=1))