如何用计算的CAGR值替换NaN列

时间:2017-02-12 10:46:11

标签: python numpy dataframe replace calculated-columns

我有一个NaN值的数据框。我想将NaN值替换为CAGR值

  val1  val2  val3  val4  val5 
0 100    100   100   100  100
1  90    110    80   110   50
2  70    150    70   NaN   NaN
3  NaN    NaN   NaN  NaN   NaN

复合年增长率(复合年增长率) =(结束值/第一个值)**(1 /年数)

例如,val1的CAGR为-23%。所以val1的最后一个值是53.9

列val4的CAGR值为10%

因此row2 NaN将为121而row3 NaN将替换为133

如何自动替换NaN?

问题是

1)我如何计算每列的CAGR?

我使用isnull()所以,我发现哪一行是空的。但我不知道如何除了计算CAGR的行。

2)如何用计算值替换NaN?

谢谢。

1 个答案:

答案 0 :(得分:0)

from __future__ import division # for python2.7
import numpy as np

# tab delimitted data
a = '''100  100 100 100 100
90  110 80  110 50
70  150 70  NaN NaN
NaN NaN NaN NaN NaN
'''

# parse and make a numpy array
data = np.array( [[np.nan if aaa=='NaN' else int(aaa) for aaa in aa.split('\t')] for aa in a.splitlines()] )

for col in range(5):

    Nyears = np.isnan(data[:,col]).argmax()-1 # row index for the last non-NaN value
    endvalue = data[Nyears,col]
    cagr = (endvalue / 100) ** (1 / Nyears)
    print Nyears, endvalue, cagr

    for year in np.argwhere(np.isnan(data[:,col])):
        data[year,col] = data[year-1,col] * cagr

print data

我明白了:

[[ 100.          100.          100.          100.          100.        ]
 [  90.          110.           80.          110.           50.        ]
 [  70.          150.           70.          121.           25.        ]
 [  58.56620186  183.71173071   58.56620186  133.1          12.5       ]]