Perform an operation on all pairs of rows in a column

前端 未结 2 678
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 13:10

Assume the following DataFrame:

id    A   
1     0
2     10
3     200
4     3000

I would like to make a calculation betweeen all rows to all ot

2条回答
  •  梦谈多话
    2021-01-21 13:15

    IIUC itertools

    import itertools
    
    s=list(itertools.combinations(df.index, 2)) 
    pd.Series([df.A.loc[x[1]]-df.A.loc[x[0]] for x in s ])
    Out[495]: 
    0      10
    1     200
    2    3000
    3     190
    4    2990
    5    2800
    dtype: int64
    

    Update

    s=list(itertools.combinations(df.index, 2)) 
    
    pd.DataFrame([x+(df.A.loc[x[1]]-df.A.loc[x[0]],) for x in s ])
    Out[518]: 
       0  1     2
    0  0  1    10
    1  0  2   200
    2  0  3  3000
    3  1  2   190
    4  1  3  2990
    5  2  3  2800
    

提交回复
热议问题