2017-08-27 183 views
0

谢谢你的建议,下面,我已经修改了我的问题,以使其更清晰Python的大熊猫ValueError异常

我有一个数据帧(BP)与平衡,以及在列1(年)的集合 - 6。

import pandas as pd 
bp = pd.DataFrame({'Balance': {0: 20000, 1: 2000, 2: 7000}, 
'1': {0: 500, 1: 400, 2: 100}, 
'2': {0: 1500, 1: 500, 2: 2000}, 
'3': {0: 0, 1: 1000, 2: 3000}, 
'4': {0: 0, 1: 500, 2: 20}, 
'5': {0: 0, 1: 50, 2: 0}, 
'6': {0: 0, 1: 0, 2: 0}, 
},columns=['Balance','1','2','3','4','5','6']) 

我试图在下一年投资余额(所以第1栏的余额应该是第1年的开始余额少收集)。但是,与此同时,如果预计没有更多收集,我想将余额记为零。

gbv = bp.copy() 

startcol =1 
endcol = 7 
for i in range(startcol,endcol): 
     gbv.iloc[:,i] = gbv.iloc[:,i-1] - bp.iloc[:,i] 
gbv[gbv < 0] = 0 

gbv 

上面的代码工作,但不写下来的余额为零,如果没有更多的征收预计,我曾尝试以下,但是这给出了一个错误。我想这是因为我正在比较行(检查bp是否有将来的集合),gbv.iloc [:,i]强制结果在总列上。不知道我应该怎么做,但。

gbv = bp.copy() 

startcol =2 
endcol = 14 
for i in range(startcol,endcol): 
    if bp.iloc[:,i:endcol].sum(axis=0) == 0: 
     gbv.iloc[:,i]= 0 
    else: 
     gbv.iloc[:,i] = gbv.iloc[:,i-1] - bp.iloc[:,i] 

gbv[gbv < 0] = 0 

gbv 



--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-22-1920f826f3ea> in <module>() 
     4 endcol = 14 
     5 for i in range(startcol,endcol): 
----> 6  if bp.iloc[:,i:endcol].sum(axis=0) == 0: 
     7   gbv.iloc[:,i]= 0 
     8  else: 

/Users/Jelmer/anaconda/lib/python3.5/site-packages/pandas/core/generic.py in __nonzero__(self) 
    951   raise ValueError("The truth value of a {0} is ambiguous. " 
    952       "Use a.empty, a.bool(), a.item(), a.any() or a.all()." 
--> 953       .format(self.__class__.__name__)) 
    954 
    955  __bool__ = __nonzero__ 

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

我试图得到下面的输出:

Balance 1  2  3  4  5  6 
0 20000 19500 18000 0  0  0  0 
1 2000 1600 1100 100  0  0  0 
2 7000 6900 4900 1900 1880 0  0 

任何建议,欢迎!

+3

究竟是什么“理想的结果”。 – MSeifert

+0

如果预计没有进一步的收藏,将余额记为零,并将余额设置为零(当收藏>余额时) – Jelmerd

+1

对不起,我应该更具体一些:请包括'gbv'应该在最后看起来如何。就像你对输入做的一样。 :)如果你有结果来验证它被正确理解*,那么理解文本就容易多了。 – MSeifert

回答

0

Got it!为了完整起见,我会在这里发布答案。诀窍是过滤未来收集为零的行。

gbv = bp.copy() 

startcol =2 
endcol = 14 
for i in range(startcol,endcol): 
     gbv.iloc[:,i] = gbv.iloc[:,i-1] - bp.iloc[:,i] 
     gbv.iloc[:,i][bp.iloc[:,i:endcol].sum(axis=1)==0] = 0 
     gbv[gbv < 0] = 0 

gbv 
0

bp.iloc [:,i:endcol]为您提供了Series,如果您想获取该系列的总和,轴应该沿着行。看起来你的代码中有一个错误。将代码的第5行更改为以下内容,看看它是否有效。

bp.iloc[:,i:endcol].sum(axis=0) == 0 

至少,你得到的错误应该消失。