Pandas dataframe中列的成对差异,以生成包含130万列的dataframe

Pandas dataframe中列的成对差异,以生成包含130万列的dataframe,pandas,dataframe,python-3.8,Pandas,Dataframe,Python 3.8,我有一个1600列的数据框 数据帧df看起来像列名为1,3,2: Row Labels 1 3 2 41730Type1 9 6 5 41730Type2 14 12 20 41731Type1 2 15 5 41731Type2 3 20 12 41732Type1 8 10 5 41732Type2 8 18 16 我需要以pythonical方式创建以下数据帧df2 Row Labels (1, 2) (1, 3) (2,

我有一个1600列的数据框

数据帧df看起来像列名为
1,3,2

Row Labels  1   3   2
41730Type1  9   6   5
41730Type2  14  12  20
41731Type1  2   15  5
41731Type2  3   20  12
41732Type1  8   10  5
41732Type2  8   18  16
我需要以pythonical方式创建以下数据帧
df2

Row Labels  (1, 2)  (1, 3)  (2, 3)
41730Type1  -4      -3       1
41730Type2  6       -2       -8
41731Type1  3       13       10
41731Type2  9       17        8
41732Type1  -3      2         5
41732Type2  8       10        2
例如,
列(1,2)
df[2]-df[1]

df2
的列名是通过将
df1
的列标题配对来创建的,这样每个名称的第二个元素大于第一个元素,例如
(1,2)、(1,3)、(2,3)


第二个挑战是pandas dataframe能否支持130万列?

我们可以对该列进行
组合
,然后创建
dict
concat

import itertools
l=itertools.combinations(df.columns,2)
d={'{0[0]}|{0[1]}'.format(x) : df[x[0]]-df[x[1]] for x in [*l]  }
newdf=pd.concat(d,axis=1)
            1|3  1|2  3|2
RowLabels                
41730Type1    3    4    1
41730Type2    2   -6   -8
41731Type1  -13   -3   10
41731Type2  -17   -9    8
41732Type1   -2    3    5
41732Type2  -10   -8    2

我们可以对列进行组合,然后创建dict和concat

import itertools
l=itertools.combinations(df.columns,2)
d={'{0[0]}|{0[1]}'.format(x) : df[x[0]]-df[x[1]] for x in [*l]  }
newdf=pd.concat(d,axis=1)
            1|3  1|2  3|2
RowLabels                
41730Type1    3    4    1
41730Type2    2   -6   -8
41731Type1  -13   -3   10
41731Type2  -17   -9    8
41732Type1   -2    3    5
41732Type2  -10   -8    2
似乎是一个显而易见的选择,与@YOBEN_S一样,使用numpy数组和dictionary是一种不同的解决方案

from itertools import combinations
new_data = combinations(df.to_numpy().T,2)
new_cols = combinations(df.columns, 2)

result = {key : np.subtract(arr1,arr2)
          if key[0] > key[1]
          else np.subtract(arr2,arr1)
          for (arr1, arr2), key
          in zip(new_data,new_cols)}

outcome = pd.DataFrame.from_dict(result,orient='index').sort_index().T

outcome


    (1, 2)  (1, 3)  (3, 2)
0   -4       -3       1
1    6       -2      -8
2    3       13      10
3    9       17       8
4   -3       2        5
5    8      10        2
似乎是一个显而易见的选择,与@YOBEN_S一样,使用numpy数组和dictionary是一种不同的解决方案

from itertools import combinations
new_data = combinations(df.to_numpy().T,2)
new_cols = combinations(df.columns, 2)

result = {key : np.subtract(arr1,arr2)
          if key[0] > key[1]
          else np.subtract(arr2,arr1)
          for (arr1, arr2), key
          in zip(new_data,new_cols)}

outcome = pd.DataFrame.from_dict(result,orient='index').sort_index().T

outcome


    (1, 2)  (1, 3)  (3, 2)
0   -4       -3       1
1    6       -2      -8
2    3       13      10
3    9       17       8
4   -3       2        5
5    8      10        2