簡體   English   中英

Python Numpy - 附加三個數組以形成矩陣或3D數組

[英]Python Numpy - attach three arrays to form a matrix or 3D array

這是我的一段代碼

一切都是一個numpy數組。 我也歡迎使用列表進行操作。

a = [1,2,3,4,5]
b = [3,2,2,2,8]

c = ['test1', 'test2', 'test3','test4','test5']

預期結果:

d = [ 1, 2, 3, 4, 5; 
      3, 2, 2, 2, 8;
      'test1','test2', 'test3', 'test4','test5' ]

要么

 d = [ 1  3   'test1';
       2   2    'test2';
       3   2   'test3';
        4   2   'test4';
        5   8    'test5']

查看concat方法。

>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
       [3, 4],
       [5, 6]])

Adam使用numpy.concat答案也是正確的,但是在指定你期望的確切形狀 - 垂直堆疊的行 - 你會想看看numpy.vstack

>>> import numpy as np
>>> np.vstack([a, b, c])
array([['1', '2', '3', '4', '5'],
       ['3', '2', '2', '2', '8'],
       ['test1', 'test2', 'test3', 'test4', 'test5']], 
        dtype='<U21')

這里有一個方法可以解決這個問題:由於你的單獨數組( int64int64<U5 )都被放在一起, 新數組將自動使用限制性最小的類型 ,在本例中是unicode類型。

另請參見: numpy.hstack

你的abc是清單; 你必須使用np.array([1,2,3])來獲得一個數組,它將顯示為[1 2 3] (沒有逗號)。

只需從這些列表中創建新列表即可生成列表列表

In [565]: d=[a,b,c]
In [566]: d
Out[566]: 
[[1, 2, 3, 4, 5],
 [3, 2, 2, 2, 8],
 ['test1', 'test2', 'test3', 'test4', 'test5']]

簡單地連接列表會產生一個更長的列表

In [567]: a+b+c
Out[567]: [1, 2, 3, 4, 5, 3, 2, 2, 2, 8, 'test1', 'test2', 'test3', 'test4', 'test5']

numpy數組存在包含數字和字符串的問題。 你必須制作一個'結構化數組'。

將這些組合成一個數組的最簡單方法是使用fromarrays實用程序函數:

In [561]: x=np.rec.fromarrays(([1,2,3],[3,2,2],['test1','test2','test3']))
In [562]: x['f0']
Out[562]: array([1, 2, 3])
In [563]: x['f2']
Out[563]: 
array(['test1', 'test2', 'test3'], 
      dtype='<U5')

In [568]: x
Out[568]: 
rec.array([(1, 3, 'test1'), (2, 2, 'test2'), (3, 2, 'test3')], 
          dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<U5')])

或者對顯示器進行一點編輯:

In [569]: print(x)
[(1, 3, 'test1') 
 (2, 2, 'test2') 
 (3, 2, 'test3')]

這不是二維數組; 這是1d(這里有3個元素),有3個字段。

也許以類似於您的規范的方式格式化此數組的最簡單方法是使用csv writer:

In [570]: np.savetxt('x.txt',x,fmt='%d  %d  %s;')
In [571]: cat x.txt     # shell command to display the file
1  3  test1;
2  2  test2;
3  2  test3;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM