1

重複の可能性:
numpy配列を2次元で拡張する最も簡単な方法は何ですか?

私はMatlabユーザーがPythonに切り替えることに不満を感じていました。なぜなら、私はすべてのトリックを知らず、それが機能するまでコードを一緒にハッキングするのに行き詰まってしまうからです。以下は、ダミー列を追加したいマトリックスがある例です。確かに、以下のzipvstackzipメソッドよりも簡単な方法があります。それは機能しますが、それは完全に初心者の試みです。教えてください。このチュートリアルに時間を割いていただき、ありがとうございます。

# BEGIN CODE

from pylab import *

# Find that unlike most things in python i must build a dummy matrix to 
# add stuff in a for loop. 
H = ones((4,10-1))
print "shape(H):"
print shape(H)
print H
### enter for loop to populate dummy matrix with interesting data...
# stuff happens in the for loop, which is awesome and off topic.
### exit for loop
# more awesome stuff happens...
# Now I need a new column on H
H = zip(*vstack((zip(*H),ones(4)))) # THIS SEEMS LIKE THE DUMB WAY TO DO THIS...
print "shape(H):"
print shape(H)
print H

# in conclusion. I found a hack job solution to adding a column
# to a numpy matrix, but I'm not happy with it.
# Could someone educate me on the better way to do this?

# END CODE
4

2 に答える 2

2

np.column_stackを使用します。

In [12]: import numpy as np

In [13]: H = np.ones((4,10-1))

In [14]: x = np.ones(4)

In [15]: np.column_stack((H,x))
Out[15]: 
array([[ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.]])

In [16]: np.column_stack((H,x)).shape
Out[16]: (4, 10)
于 2012-09-25T02:02:59.753 に答える
0

異なる次元の配列を連結できる関数がいくつかあります。

あなたの場合、np.hstackあなたが望むものに見えます。np.column_stackセットの 1D 配列を 2D 配列としてスタックしますが、開始する 2D 配列が既にあります。

もちろん、難しい方法で行うことを妨げるものは何もありません。

>>> new = np.empty((a.shape[0], a.shape[1]+1), dtype=a.dtype)
>>> new.T[:a.shape[1]] = a.T

ここでは、余分な列を持つ空の配列を作成し、いくつかのトリックを使用して最初の列をに設定しましたa(転置演算子を使用して、...に比べて余分な行Tを持っています)。new.Ta.T

于 2012-09-25T08:19:10.313 に答える