此代码曾经有效,现在不再有效。对于我的生活,我无法弄清楚哪里出了问题。我猜想它与for循环有关,仅此而已。
import pandas as pd
LastFY = 2017
n = 15
DeclRate = 0.1
Res = 442.364
LFY_Vol = 27.8
Col_Names = ['Year', 'Reserves', 'Prod']
df = pd.DataFrame(columns=Col_Names)
df_add = pd.DataFrame(columns=Col_Names)
df['Year'] = [LastFY]
df['Prod'] = [LFY_Vol]
df['Reserves'] = [Res]
for i in range(1, n+1):
FY = df['Year'][i-1] + 1
if df['Prod'][i-1] * (1 - DeclRate) > df['Reserves'][i-1]:
Prod_A = df['Reserves'][i-1]
else:
Prod_A = df['Prod'][i-1] * (1 - DeclRate) if i < n else df['Reserves'][i-1]
Reserves_A = df['Reserves'][i-1] - Prod_A
df_add['Year'] = [FY]
df_add['Reserves'] = [Reserves_A]
df_add['Prod'] = [Prod_A]
df = df.append(df_add, ignore_index=True)
df.round(0).style
谢谢。
这是我得到的错误代码...
runfile('C:/Users.../TEST.py', wdir='C:/Users...')
Traceback (most recent call last):
File "<ipython-input-175-365e0e41c561>", line 1, in <module>
runfile('C:/Users.../TEST.py', wdir='C:/Users...')
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users.../TEST.py", line 22, in <module>
FY = df['Year'][i-1] + 1
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py", line 623, in __getitem__
result = self.index.get_value(self, key)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 2560, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandas/_libs/index.pyx", line 83, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 91, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 811, in pandas._libs.hashtable.Int64HashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 817, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: -1
答案 0 :(得分:0)
您对n
的定义如下:
n = 15
然后,您定义一行数据框:
print(df)
Year Reserves Prod
0 2017 442.364 27.8
然后您遍历range(1, 16)
:
for i in range(1, n+1):
FY = df['Year'][i-1] + 1
但是,由于您的数据框仅包含索引为0
的一行,因此df['Year'][1]
将返回KeyError
。这正是您应该期望的。
您尚未说明要达到的目标。您可能希望在a new question中这样做。上面的说明描述了为什么获得错误。通常,print
是确定每个阶段发生情况的有用函数。