簡體   English   中英

Pandas來自groupby的累積差異

[英]Pandas cumulative diff from groupby

我需要計算從MultiIndex級別開始的差異,以計算從級別開始的衰減。 我的示例輸入和輸出將如下所示:

               values
place time     
A     a           120
      b           100
      c            90
      d            50
B     e            11
      f            12
      g            10
      h             9

               values

A     a           NaN
      b           -20
      c           -30
      d           -70
B     e           Nan
      f            +1
      g            -1
      h            -2

我可以使用grouby來獲取級別中連續單元格之間的差異:

df.groupby(level=0)['values'].diff()

但這不是我想要的!

唉,接受的答案並不是我想要的。 我有一個更好的例子:

arrays = [np.array(['bar', 'bar', 'bar', 'foo', 'foo', 'foo']),
          np.array(['one', 'two', 'three', 'one', 'two', 'three'])]
df = pd.DataFrame([1000, 800, 500, 800, 400, 200], index=arrays)

   bar one    1000
       two     800
       three   500
   foo one     800
       two     400
       three   200

    expected_result = pd.DataFrame([Nan, -200, -500, Nan, -400, -600], index=arrays)

   bar one      Nan
       two     -200
       three   -500
   foo one     Nan 
       two     -400
       three   -600

但是df.groupby(level=0).diff().cumsum()給出:

pd.DataFrame([Nan, -200, -500, Nan, -900, -1100], index=arrays)

   bar one      Nan
       two     -200
       three   -500
   foo one      Nan 
       two     -900
       three   -1100

你在尋找一個cumsum嗎?

df.groupby(level=0)['values'].diff().cumsum()

你可以得到我想要通過鏈接另一groupby

arrays = [np.array(['bar', 'bar', 'bar', 'foo', 'foo', 'foo']),
      np.array(['one', 'two', 'three', 'one', 'two', 'three'])]
df = pd.DataFrame([1000, 800, 500, 800, 400, 200], index=arrays)

   bar one    1000
       two     800
       three   500
   foo one     800
       two     400
       three   200

    expected_result = pd.DataFrame([Nan, -200, -500, Nan, -400, -600], index=arrays)

df.groupby(level=0).diff().groupby(level=0).cumsum()

    bar one      Nan
       two     -200
       three   -500
    foo one     Nan 
       two     -400
       three   -600

暫無
暫無

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

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