我正在编写一个函数,该函数获取股票的收盘价并计算与前一个日期相比的变化百分比
def daily_return(df):
df_daily_return = df.copy()
for i in df.columns[1:]:
# Loop through each row belonging to the stock
for j in range(1, len(df)):
# Calculate the percentage of change from the previous day
df_daily_return[i][j] = ((df[i][j]- df[i][j-1])/df[i][j-1]) * 100
# set the value of first row to zero, as previous value is not available
df_daily_return[i][0] = 0
return df_daily_return`
stocks_daily_return = daily_return(stocks_df)
stocks_daily_return
现在给定函数中存在问题,我收到关键错误
KeyError: 1
我做错了什么?
没什么,因为我是这一切的新手
您无法通过
df[]
选择数据帧的单行。您只能使用它来切片数据帧的范围。请使用 df.iloc[i]
来代替。