子集和转置python数组

时间:2013-07-14 00:18:09

标签: python arrays python-2.7 subset transpose

我有一个数组:

[['a','1'.'2','3','4'],['b','5','6','7','8'],['c','9','10','11','12'],['d','13','14','15','16']]

我想将其子集化并转置。为了转置它我尝试了zip函数,但它输出数组,当我写入csv文件时没有格式为制表符分隔。

所需的输出:

a   b
1   5
2   6
3   7
4   8
c   d
9   13
10   14
11   15
12   16

由于我无法在此处制作标签,因此我会在输出中留下三个空格。

1 个答案:

答案 0 :(得分:1)

这样可以使输出看起来像您要查找的内容:

import numpy as np

a = np.array([['a','1','2','3','4'],
              ['b','5','6','7','8'],
              ['c','9','10','11','12'],
              ['d','13','14','15','16']])

new_a = np.hstack((a[:2,], a[2:])).T

结果:

>>> new_a
array([['a', 'b'],
       ['1', '5'],
       ['2', '6'],
       ['3', '7'],
       ['4', '8'],
       ['c', 'd'],
       ['9', '13'],
       ['10', '14'],
       ['11', '15'],
       ['12', '16']], 
      dtype='|S2')