数据框-pandas/python中列的所有可能组合 [英] All possible combinations of columns in dataframe -pandas/python

查看:60
本文介绍了数据框-pandas/python中列的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试采用一个数据帧并创建另一个数据帧,并使用所有可能的列组合以及相应值之间的差,即11-apr列AB上的(B-A)= 0等.

I'm trying to take one dataframe and create another, with all possible combinations of the columns and the difference between the corresponding values, i.e on 11-apr column AB should be (B-A)= 0 etc.

例如,以

        Dt              A           B           C          D
        11-apr          1           1           1          1
        10-apr          2           3           1          2

我如何获得一个新的框架,如下所示:

how do I get a new frame that looks like this:

我遇到了以下帖子,但无法将其转置为专栏文章.

I have come across the below post, but have not been able to transpose this to work for columns.

使用熊猫聚合所有数据框行对组合

推荐答案

您可以使用:

from itertools import combinations
df = df.set_index('Dt')

cc = list(combinations(df.columns,2))
df = pd.concat([df[c[1]].sub(df[c[0]]) for c in cc], axis=1, keys=cc)
df.columns = df.columns.map(''.join)
print (df)
        AB  AC  AD  BC  BD  CD
Dt                            
11-apr   0   0   0   0   0   0
10-apr   1  -1   0  -2  -1   1

这篇关于数据框-pandas/python中列的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆