简体   繁体   English

Column_match([[1],[1,1]])<-如何使尺寸与NA值匹配?

[英]Column_match([[1],[1,1]]) <— how to make dimensions match with NA values?

Any flag for this? 为此有任何标志吗? Please, see the intended. 请看预期的。

>>> numpy.column_stack([[1], [1,2]])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/pymodules/python2.7/numpy/lib/shape_base.py", line 296, in column_stack
    return _nx.concatenate(arrays,1)
ValueError: array dimensions must agree except for d_0

Input 输入项

[[1],[1,2]]

Intended Output 预期输出

[[NA,1], [1,2]]

In general 一般来说

[[1],[2,2],[3,3,3],...,[n,n,n,n,n...,n]]

to

[[NA, NA, NA,..., NA,1], [NA, NA, ..., 2, 2], ...[n,n,n,n,n]]

where the columns may be a triangluar zero matrix initially. 其中列最初可能是三角三角零矩阵。 Yes you can understand the term NA as None. 是的,您可以将术语“ NA”理解为“无”。 I got the triangular matrix almost below. 我几乎在下面得到了三角形矩阵。

>>> a=[[1],[2,2],[3,3,3]]
>>> a
[[1], [2, 2], [3, 3, 3]]
>>> len(a)
3
>>> [aa+['']*(N-len(aa)) for
... 
KeyboardInterrupt
>>> N=len(a)
>>> [aa+['']*(N-len(aa)) for aa in a]
[[1, '', ''], [2, 2, ''], [3, 3, 3]]
>>> transpose([aa+['']*(N-len(aa)) for aa in a])
array([['1', '2', '3'],
       ['', '2', '3'],
       ['', '', '3']], 
      dtype='|S4')

a pure numpy solution: 一个纯粹的numpy解决方案:

>>> lili = [[1],[2,2],[3,3,3],[4,4,4,4]]
>>> y = np.nan*np.ones((4,4))
>>> y[np.tril_indices(4)] = np.concatenate(lili)
>>> y
array([[  1.,  nan,  nan,  nan],
       [  2.,   2.,  nan,  nan],
       [  3.,   3.,   3.,  nan],
       [  4.,   4.,   4.,   4.]])

>>> y[:,::-1]
array([[ nan,  nan,  nan,   1.],
       [ nan,  nan,   2.,   2.],
       [ nan,   3.,   3.,   3.],
       [  4.,   4.,   4.,   4.]])

I'm not sure which triangular array you want, there is also np.triu_indices 我不确定您想要哪个三角形数组,也有np.triu_indices

(maybe not always faster, but easy to read) (也许并不总是更快,但易于阅读)

column_stack adds a column to an array. column_stack将一列添加到数组。 That column is supposed to be a smalled (1D) array. 该列应该是缩小(1D)数组。

When I try : 当我尝试:

from numpy import *
x = array([0])
z = array([1, 2])

if you do this : 如果您这样做:

r = column_stack ((x,z))

You'll get this : 您将得到:

>>> array([0,1,2])

So, in order to add a column to your first array, maybe this : 因此,为了将列添加到您的第一个数组,也许可以这样:

n = array([9])

arr = ([column_stack((n, x))], z)

It shows up this : 它显示如下:

>>> arr
([array([[9, 0]])], array([[1, 2]]))

It has the same look as your "intended output" 它的外观与您的“预期输出”相同

Hope this was helpful ! 希望这对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM