2021年4月12日星期一

How to find difference between rows in a pandas multiIndex, by level 1

Suppose we have a DataFrame like this, only with many, many more index A values:

df = pd.DataFrame([[1,2,1,2],                [1,1,2,2],                [2,2,1,0],                [1,2,1,2],                [2,1,1,2]    ], columns=['A','B','c1','c2'])  df.groupby(['A','B']).sum()    ## result       c1  c2  A B          1 1   2   2    2   2   4  2 1   1   2    2   1   0    

How can I get a data frame that consists of the difference between rows, by the second level of the index, level B? The output here would be

A    c1  c2  1     0  -2  2     0   2  

Note In my particular use case, I have a lot of column A values, so I can write out the value for A explicitly.

https://stackoverflow.com/questions/67067203/how-to-find-difference-between-rows-in-a-pandas-multiindex-by-level-1 April 13, 2021 at 08:21AM

没有评论:

发表评论