python - 如何阅读第 1 列和第 2 列,以及第 n 列到最后一列。麻木的
问题描述
我有一个多维数组,我需要分别选择第 1 列和第 2 列、第 1 列和第 3 列、第 1 列和第 4 列。然后是第 2 列和第 3 列,第 2 列和第 4 列,最后是第 3 列和第 4 列。等等......为了声明的目的,我转置了数组。
我的代码
import pandas as pd
pole= np.array([[11,12,13,14],[21,22,23,24],[31,32,33,34],[41,42,43,44]])
pole=np.transpose(pole)
print(pole)
我需要
#1st and 2nd
11 21
12 22
13 23
14 24
#1st and 3rd
11 31
12 32
13 33
14 34
#1st and 4th
11 41
12 42
13 43
14 44
#2nd and 3rd
21 31
22 32
23 33
24 34
#2nd and 4th
21 41
22 42
23 43
24 44
#3rd and 4th
31 41
32 42
33 43
34 44
解决方案
使用以下非常简洁的代码:
result = np.concatenate([ np.c_[pole[:,x], pole[:,y]]
for x, y in np.c_[np.triu_indices(n=pole.shape[1], k=1)] ])
细节:
np.c_[pole[:,x], pole[:,y]]
- 生成结果的“段” - 列x和y的串联,for x, y in ...
- 生成一系列列索引对,np.concatenate
- 执行上述“段”的垂直连接。
结果,对于您的样本(极点)是:
array([[11, 21],
[12, 22],
[13, 23],
[14, 24],
[11, 31],
[12, 32],
[13, 33],
[14, 34],
[11, 41],
[12, 42],
[13, 43],
[14, 44],
[21, 31],
[22, 32],
[23, 33],
[24, 34],
[21, 41],
[22, 42],
[23, 43],
[24, 44],
[31, 41],
[32, 42],
[33, 43],
[34, 44]])