水平连接numpy向量和矩阵

时间:2015-10-29 02:57:46

标签: python arrays numpy matrix

我有以下numpy向量set viewoptions+=cursor,folds,slash,unix set viewoptions-=options augroup vimrc autocmd BufWritePost * \ if expand('%') != '' && &buftype !~ 'nofile' \| mkview \| endif autocmd BufRead * \ if expand('%') != '' && &buftype !~ 'nofile' \| silent loadview \| endif augroup END 和矩阵import java.util.Scanner; public class Project{ static int diff; public static int calcSeq(int num){ return num+diff; } public static void main(String[] args){ Scanner keyboard = new Scanner(System.in); int diff = (int)(Math.random()*20)+1; int term1 = (int)(Math.random()*10)+1; int sum = term1; int ans = 0; System.out.println(term1); for (int i = 1; i<=4; i=i+1){ int nextTerm = calcSeq(term1); sum = sum + nextTerm; System.out.println(sum); } int term6 = sum + diff; System.out.println(term6); System.out.print("Enter the sixth term of this arithmetic sequence: "); ans = keyboard.nextInt(); if (ans == term6){ System.out.println("That is the correct answer."); } else if (ans != term6){ System.out.println("That is incorrect. Try again."); } } }

m

我想要做的是将它们水平连接,产生

n

该怎么做?

我尝试了但失败了:

import numpy as np
m = np.array([360., 130., 1.])
n = np.array([[60., 90., 120.], 
              [30., 120., 90.],
              [1.,  1.,   1. ]])

2 个答案:

答案 0 :(得分:6)

>>> np.hstack((n,np.array([m]).T))
array([[  60.,   90.,  120.,  360.],
       [  30.,  120.,   90.,  130.],
       [   1.,    1.,    1.,    1.]])

问题在于,由于m只有一个维度,因此其转置仍然相同。在进行转置之前,你需要使它具有形状(1,3)而不是(3,)。

更好的方法是np.hstack((n,m[:,None])),如DSM在评论中所建议的那样。

答案 1 :(得分:3)

实现目标的一种方法是将m转换为list list

import numpy as np
m = np.array([360., 130., 1.])
n = np.array([[60., 90., 120.],
              [30., 120., 90.],
              [1.,  1.,   1. ]])
m = [[x] for x in m]
print np.append(n, m, axis=1)

另一种方法是使用np.c_

import numpy as np
m = np.array([360., 130., 1.])
n = np.array([[60., 90., 120.],
              [30., 120., 90.],
              [1.,  1.,   1. ]])
print np.c_[n,m]