数据框中列的配对差异生成具有 130 万列的数据框
Paired difference of columns in dataframe to generate dataframe with 1.3 million columns
我有一个包含 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
我需要用 Python 方式创建以下数据框 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
例如column (1, 2)
由 df[2] - df[1]
创建
df2
的列名称是通过将 df1
的列 headers 配对创建的,这样每个名称的第二个元素大于第一个元素,例如(1, 2), (1, 3), (2, 3)
第二个挑战是 pandas 数据框可以支持 130 万列吗?
我们可以为列做 combinations
,然后创建 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
itertools combinations 似乎是显而易见的选择,与@YOBEN_S 相同,解决方案的不同途径,使用 numpy 数组和字典
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
我有一个包含 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
我需要用 Python 方式创建以下数据框 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
例如column (1, 2)
由 df[2] - df[1]
df2
的列名称是通过将 df1
的列 headers 配对创建的,这样每个名称的第二个元素大于第一个元素,例如(1, 2), (1, 3), (2, 3)
第二个挑战是 pandas 数据框可以支持 130 万列吗?
我们可以为列做 combinations
,然后创建 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
itertools combinations 似乎是显而易见的选择,与@YOBEN_S 相同,解决方案的不同途径,使用 numpy 数组和字典
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