我有一个dataframe如下:
Class Value1 Value2
A 2 1
B 3 3
C 4 5
我希望生成所有可能的配对,输出 Dataframe 如下所示
Class Value1 Value2 A_Value1 A_Value2 B_Value1 B_Value2 C_Value1 C_Value2
A 2 1 2 1 3 3 4 5
B 3 3 2 1 3 3 4 5
C 4 5 2 1 3 3 4 5
请假设有将近1000个这样的类。有没有什么有效的方法可以做到这一点?最终,我想找出每个对中(Value1和value2)之间的差异
编辑:A_B_Value是根据公式创建的
A_B_Value = absolute(ClassA_value1 - ClassB_value1) + absolute(ClassA_value2 - ClassB_value2)
Class Value1 Value2 A_B_Value A_C_Value B_C_Value
A 2 1 3 6 3
B 3 3 3 6 3
C 4 5 3 6 3
谢谢你
2条答案
按热度按时间bxjv4tth1#
您可以
stack
并展平MultiIndex,然后执行交叉merge
:输出:
矢量数值计算
输出:
vs3odd8k2#
如果需要减去列
Value1,Value2
并追加新列,则创建字典并通过DataFrame.assign
添加它们:编辑:你可以通过
itertools.combinations
创建所有的组合,并在字典理解中获取差异,最后通过DataFrame.assign
创建新的列:EDIT1:因为性能很重要,这里是受this启发的矢量化解决方案:
性能比较:
一个三个三个一个