簡體   English   中英

將負行值與前幾行相加 pandas

[英]Sum negative row values with previous rows pandas

我很難找到一種好方法來查找列中的所有負條目並將它們向上移動,將它們與現有條目相加(即從當前條目中減去負條目),直到所有值都是正數。

重要的是最終 dataframe 沒有負值,並且所有以前的負條目 = 0。此外,該表是重復的,這意味着我需要根據 ID 和條目匯總結果(僅對相同 ID 的條目進行求和)。

基於此處已提供的表格:

當下:

ID 日期 參賽作品
1 2013 100
1 2014 0
1 2015 60
1 2016 -30
1 2017 0
1 2018 50
1 2019 0
1 2020 -20
2 2013 100
2 2014 0
2 2015 60
2 2016 -30
2 2017 0
2 2018 50
2 2019 0
2 2020 -20

期望:

ID 日期 參賽作品
1 2013 100
1 2014 0
1 2015 30
1 2016 0
1 2017 0
1 2018 30
1 2019 0
1 2020 0
2 2013 100
2 2014 0
2 2015 30
2 2016 0
2 2017 0
2 2018 30
2 2019 0
2 2020 0

您可以在創建組后嘗試反向 cumsum,然后屏蔽:

s = df['Entries'].gt(0).cumsum()
u= df['Entries'][::-1].groupby(s).cumsum().mask(df['Entries'].le(0),0)
out = df.assign(New_Entries=u) # you can assign to the original column too.

print(out)
    ID  Date  Entries  New_Entries
0    1  2013      100          100
1    1  2014        0            0
2    1  2015       60           30
3    1  2016      -30            0
4    1  2017        0            0
5    1  2018       50           30
6    1  2019        0            0
7    1  2020      -20            0
8    2  2013      100          100
9    2  2014        0            0
10   2  2015       60           30
11   2  2016      -30            0
12   2  2017        0            0
13   2  2018       50           30
14   2  2019        0            0
15   2  2020      -20            0

值數組上的直接遞歸 function

df = pd.read_csv(io.StringIO("""ID  Date    Entries
1   2013    100
1   2014    0
1   2015    60
1   2016    -30
1   2017    0
1   2018    50
1   2019    0
1   2020    -20
2   2013    100
2   2014    0
2   2015    60
2   2016    -30
2   2017    0
2   2018    50
2   2019    0
2   2020    -20"""), sep="\t")

def shiftminus(a):
    touch=False
    for i,n in enumerate(a):
        if n<0 and i>0:
            a[i-1] += a[i]
            a[i] = 0
            touch=True
    if touch:
        a = shiftminus(a)
    return a

df["Entries"] = shiftminus(df["Entries"].values)


output

 ID  Date  Entries
  1  2013      100
  1  2014        0
  1  2015       30
  1  2016        0
  1  2017        0
  1  2018       30
  1  2019        0
  1  2020        0
  2  2013      100
  2  2014        0
  2  2015       30
  2  2016        0
  2  2017        0
  2  2018       30
  2  2019        0
  2  2020        0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM