2017-03-07 79 views
2

我正在与一个帧工作像熊猫:柱的成对级联矢量

df = pd.DataFrame({ 
'G1':[1.00,0.69,0.23,0.22,0.62], 
'G2':[0.03,0.41,0.74,0.35,0.62], 
'G3':[0.05,0.40,0.15,0.32,0.19], 
'G4':[0.30,0.20,0.51,0.70,0.67], 
'G5':[0.40,0.36,0.88,0.10,0.19] 
}) 

,我想操纵它,使得列是当前列的成对排列例如所有列现在都是10个元素,例如列'G1:G2'将在列'G1'后面添加列'G2'。我附上了一张模拟图片。请注意,pic已经命名索引,与上面的示例代码不同。我可以使用或不使用索引。

我该怎么办?我可以创建一个函数来处理每一列,但我认为函数必须返回一个与所有其他列串联的数据框。不知道那会是什么样子。

enter image description here

回答

1

这里是一个办法,但我怀疑可能还有一个办法直接在大熊猫

from itertools import permutations 

'''Get all the column permutations''' 
lst = [x for x in permutations(df.columns, 2)] 

'''Create a list of columns names''' 
names = [x[0]+'_'+x[1] for x in lst] 

'''Create the new arrays by vertically stacking pairs of column values''' 
cols = [np.vstack((df[x[0]].values,df[x[1]].values)).ravel() for x in lst] 

'''Create a dictionary with column names as keys and the arrays as values''' 
d = dict(zip(names, cols)) 

'''Create new dataframe from dict''' 
df2 = pd.DataFrame(d) 

df2 

    G1_G2 G1_G3 G1_G4 G1_G5 G2_G1 G2_G3 G2_G4 G2_G5 G3_G1 G3_G2 \ 
0 1.00 1.00 1.00 1.00 0.03 0.03 0.03 0.03 0.05 0.05 
1 0.69 0.69 0.69 0.69 0.41 0.41 0.41 0.41 0.40 0.40 
2 0.23 0.23 0.23 0.23 0.74 0.74 0.74 0.74 0.15 0.15 
3 0.22 0.22 0.22 0.22 0.35 0.35 0.35 0.35 0.32 0.32 
4 0.62 0.62 0.62 0.62 0.62 0.62 0.62 0.62 0.19 0.19 
5 0.03 0.05 0.30 0.40 1.00 0.05 0.30 0.40 1.00 0.03 
6 0.41 0.40 0.20 0.36 0.69 0.40 0.20 0.36 0.69 0.41 
7 0.74 0.15 0.51 0.88 0.23 0.15 0.51 0.88 0.23 0.74 
8 0.35 0.32 0.70 0.10 0.22 0.32 0.70 0.10 0.22 0.35 
9 0.62 0.19 0.67 0.19 0.62 0.19 0.67 0.19 0.62 0.62 

这是输出

为了避免创建的部分做列出并使用itertools.permutations是一个生成器的事实:

d = dict((x[0]+'_'+x[1] , np.vstack((df[x[0]].values,df[x[1]].values)).ravel()) 
         for x in permutations(df.columns, 2)) 

df2 = pd.DataFrame(d) 
2

我会做这样的

from itertools import permutations 

l1, l2 = map(list, zip(*permutations(range(len(df.columns)), 2))) 

v = df.values 
pd.DataFrame(
    np.vstack([v[:, l1], v[:, l2]]), 
    list(map('S{}'.format, range(1, len(df) + 1))) * 2, 
    df.columns.values[l1] + ':' + df.columns.values[l2] 
) 

enter image description here

+0

好nigth太;) – jezrael