什么是2维扩展numpy的阵列最简单的方法? [英] What's the simplest way to extend a numpy array in 2 dimensions?

查看:229
本文介绍了什么是2维扩展numpy的阵列最简单的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维数组,看起来像这样:

  XX
XX

什么是添加一个额外的行和列的最有效的方式:

  XXY
XXY
YYY

有关加分,我希望也能敲出单行和列,因此,例如在矩阵下面我想能够击倒所有的一个的只留下X的的 - 特别是我试图删除第n行,并在同一时间n列 - 我希望能够尽快做到这一点越好:

  xxaxx
xxaxx
AAAAA
xxaxx
xxaxx


解决方案

在我能想到的code线方面最短的是第一个问题。

 >>>导入numpy的是NP
>>> p值= np.array([1,2],[3,4])>>> p值= np.append(ρ,[5,6],0)
>>> p值= np.append(ρ,[7],[8],[9],1)>>> p
阵列([[1,2,7],
   [3,4,8],
   [5,6,9]])

而对于第二个问题

  P = np.array(范围(20))
>>> p.shape =(4,5)
>>> p
阵列([0,1,2,3,4],
       [5,6,7,8,9],
       [10,11,12,13,14],
       [15,16,17,18,19]])
>>> N = 2
>>> p值= np.append(第[:N],第[n + 1个:],0)
>>> p值= np.append(第[...,:N],第[...,N + 1:],1)
>>> p
阵列([0,1,3,4],
       [5,6,8,9],
       [15,16,18,19]])

I have a 2d array that looks like this:

XX
xx

What's the most efficient way to add an extra row and column:

xxy
xxy
yyy

For bonus points, I'd like to also be able to knock out single rows and columns, so for example in the matrix below I'd like to be able to knock out all of the a's leaving only the x's - specifically I'm trying to delete the nth row and the nth column at the same time - and I want to be able to do this as quickly as possible:

xxaxx
xxaxx
aaaaa
xxaxx
xxaxx

解决方案

The shortest in terms of lines of code i can think of is for the first question.

>>> import numpy as np
>>> p = np.array([[1,2],[3,4]])

>>> p = np.append(p, [[5,6]], 0)
>>> p = np.append(p, [[7],[8],[9]],1)

>>> p
array([[1, 2, 7],
   [3, 4, 8],
   [5, 6, 9]])

And the for the second question

    p = np.array(range(20))
>>> p.shape = (4,5)
>>> p
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
>>> n = 2
>>> p = np.append(p[:n],p[n+1:],0)
>>> p = np.append(p[...,:n],p[...,n+1:],1)
>>> p
array([[ 0,  1,  3,  4],
       [ 5,  6,  8,  9],
       [15, 16, 18, 19]])

这篇关于什么是2维扩展numpy的阵列最简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆