簡體   English   中英

總和 DataFrame 行一列包含 substring

[英]Sum DataFrame rows a column contains a substring

我有這個 DataFrame:

df1:
      Date Value       Info
        1    1    XXX.othertext2
        1    4    somerandomtext
        1    2    XXX.othertext2
        1    3    XXX.othertext3
        1    2    XXX.othertext3
        1    1    XXX.othertext2
        1    1    XXX.othertext3
        2    6    somerandomtext
        2    9    XXX.othertext2

我想對以XXX.othertext2開頭的同一Date的行求和,直到新的XXX.othertext2sometext (所以它是第一個XXX.othertext2 + 所有XXX.othertext3的總和)。 Info的結果行值將是XXX.othertext2

newdf:
          Date Value      Info
            1    1    XXX.othertext2
            1    4    somerandomtext
            1    7    XXX.othertext2
            1    2    XXX.othertext2
            2    6    sometext
            2    9    XXX.othertext2

這是一個選項,帶有自定義grouper

grouper = ((b.Info.str.contains('some')) | (b.Info == 'XXX.othertext2')).cumsum()
b.groupby(['Date', grouper]).sum().reset_index()

如有必要,您可以使用正則表達式對其進行更多改進。

暫無
暫無

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

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