PythonPandas价值

2024-06-26 14:16:46 发布

您现在位置:Python中文网/ 问答频道 /正文

谢谢你的建议,我已经修改了我的问题,使它更清楚

我有一个带有余额的数据帧(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列中的余额应该是第一年开始的余额减去收款)。但是,如果我不想在同一时间将余额减记为零。在

^{pr2}$

上面的代码可以工作,但是不会将余额减记为零,如果不需要更多的集合,我尝试了以下方法,但这会产生一个错误。我想这是因为我正在比较行(检查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

欢迎有任何建议!在


Tags: inpandasforrange建议余额pdbool
2条回答

明白了!为了完整起见,我将把答案贴在这里。诀窍是过滤未来集合为零的行。在

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

在英国石油公司[:,i:endcol]给你一个级数,如果你想取这个级数的和,轴应该是沿着行的。看起来你的代码中有一个bug。将代码的第5行改为下面的代码,看看它是否有效。在

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

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

相关问题 更多 >