我定义了一个函数来计算 CAGR。我有不同的年度数据列,有些列不完整(数据不可用时为 0)。对于那些 df 列长度数据不完整的人,我想找到数据为 0 的位置,并计算 df_periods 中定义的过去 n 年的 cagr。我对 python 很陌生,所以不知道该怎么做。
df=
col1 col2 col3 col4 col5
8 9 6 7 1
8 9 6 7 1
8 9 6 7 1
8 9 6 7 1
8 9 6 7 1
8 0 6 7 0
8 0 6 7 0
8 0 6 7 0
df_periods=
col1 col2 col3 col4 col5
4 3 5 4 4
def cagr(startval , endval , periods ):
return (endval / startval) ** (1 / (periods - 1)) - 1
我已经遍历 df 以在数据帧中有 0 个值的地方返回 true(数据不完整的地方)——但我不知道如何实际提取数据为零的引用,并仅将 cagr 函数应用于 0 值之前的 n 年。
find_zero = df.apply(lambda x: x == 0)
#CAGR values -- how can I get these to reference the first true value in each column? I don't think these work
endval = df.iloc[lambda x: x.index == 0] -1
startval = df.iloc[]
periods = df_periods.iloc[]