Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 动态分配值_Python_Pandas - Fatal编程技术网

Python 动态分配值

Python 动态分配值,python,pandas,Python,Pandas,我有一个数据框,上面有姓名、现金、日期等列。在数据框b中,我想动态填充xnpv值 def xnpv(rate, values, dates): if rate <= -1.0: return float('inf') d0 = dates.min() # or min(dates) return sum([ vi / (1.0 + rate)**((di - d0).days / 365.0) for vi, di in zip(values,

我有一个数据框,上面有姓名、现金、日期等列。在数据框
b
中,我想动态填充xnpv值

def xnpv(rate, values, dates):
    if rate <= -1.0:
        return float('inf')
    d0 = dates.min()   # or min(dates)
    return sum([ vi / (1.0 + rate)**((di - d0).days / 365.0) for vi, di in zip(values, dates)])

for cl in range(2,ctr_max+1,1):    
    grouped = b.groupby('Name')         
    b["XNPV"+str(cl)]=grouped.apply(lambda x: xnpv(0.1, 
    x[str(cl)+"cash"], x['Value Date']))
def xnpv(速率、值、日期):
如果速率我相信您需要自定义函数:

b = pd.DataFrame({"Name":['a','a','a','a','b','b','c','c'],
              "2cash":[1,1,3,4,1,2,4,5],
              "3cash":[4,5,3,2,4,5,7,9],
              "4cash":[1,1,2,4,5,1,3,4],
              "Value Date":['2017-01-01','2017-02-01','2017-03-01','2017-04-01',
                     '2017-01-01','2017-02-01','2017-03-01','2017-04-01']
             })
b["Value Date"] = pd.to_datetime(b["Value Date"])

def xnpv(速率、值、日期):
您是否可以添加一些示例数据?
def xnpv(rate, values, dates):
    if rate <= -1.0:
        return float('inf')
    d0 = dates.min()   # or min(dates)
    return sum([ vi / (1.0 + rate)**((di - d0).days/ 365.0) for vi, di in zip(values, dates)])

ctr_max = 4
def f(x):
    for cl in range(2,ctr_max+1,1): 
        x["XNPV{}".format(cl)] = xnpv(0.1, x["{}cash".format(cl)], x['Value Date'])
    return x

df = b.groupby('Name').apply(f)
print (df)
  Name  2cash  3cash  4cash Value Date     XNPV2      XNPV3     XNPV4
0    a      1      4      1 2017-01-01  8.853165  13.867370  7.868453
1    a      1      5      1 2017-02-01  8.853165  13.867370  7.868453
2    a      3      3      2 2017-03-01  8.853165  13.867370  7.868453
3    a      4      2      4 2017-04-01  8.853165  13.867370  7.868453
4    b      1      4      5 2017-01-01  2.983876   8.959689  5.991938
5    b      2      5      1 2017-02-01  2.983876   8.959689  5.991938
6    c      4      7      3 2017-03-01  8.959689  15.927441  6.967751
7    c      5      9      4 2017-04-01  8.959689  15.927441  6.967751