Python更改数据帧顺序值

2024-04-20 10:38:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试更改dataframe打印输出,以便它开始将第一个dataframe条目编号为40,而不是0

import pandas as pd
import numpy as np
import glob
import datetime as dt
import math

principle = 50000 # Amount initially invested
rate_of_return = .076 # Return on investment or the interest rate
years = 26 # Assuming starting at age 40 and end at age 65

roi_list = []
for i in range(years):
    roi_list.append(principle)  
    principle = principle*(math.exp(rate_of_return)) 

df = pd.DataFrame(roi_list) # Creates a dataframe containing the roi_list values
print(df)

Tags: oftheimportdataframeagereturnrateas
3条回答

pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)采用index参数来提供索引信息

index : Index or array-like

Index to use for resulting frame. Will default to np.arange(n) if no indexing information part of input data and no index provided

这样就可以了:

df = pd.DataFrame(roi_list, index=np.arange(40, 40 + years))

因为您使用的是pandas,所以您可能需要考虑一个矢量化的解决方案。这就是熊猫的设计目的

years = np.arange(26)
r = .076  # 7.6% compounded annual growth rate
principle = 50000

s = pd.Series(principle * ((1+r)**years),
              index=np.add(years, 40))

print(s.head())
40    50000.000
41    53800.000
42    57888.800
43    62288.349
44    67022.263
dtype: float64

演练:

  • years = np.arange(26)创建一个从0开始到25结束的NumPy数组
  • r是我们的年化增长率。你在评论中说你假设的是指数增长率,但事实似乎并非如此。你目前使用的年化增长率e提高到.076(math.exp(r)),年化增长率为7.89%。这是一个恒定的增长率,而不是指数增长率
  • 这里的重要术语是principle * ((1+r)**years)。仅仅拿(1+r)**years就可以显示出1美元的年复合增长率为7.6%。将(整个数组)乘以你的开始原则,得到该原则的假设增长
df = pd.DataFrame(roi_list,index=range(40,40+years),columns=['Principle'])

相关问题 更多 >