How to fill an NPArray with another array starting at a key in Python?

拟墨画扇 提交于 2019-12-11 06:03:26

问题


I have a dataframe, called x. This consists of 2 columns which looks like this (712, 2):

     SibSp  Parch
731      0      0
230      1      0
627      0      0
831      1      1
391      0      0
.................

Due to logistic regression needing a 'free weight', I build a newX variable with the shape of my x data frame but blank values.

newX = np.zeros(shape=(x.shape[0], x.shape[1] + 1))

This generates a (712, 3) np array:

[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]
 ...
 [0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

Since the first index (0) is a free weight, I want to now assign my x values to index 1 and 2.

newX[:, 1:] = x

However, it gives me this error:

Exception: Dot product shape mismatch, (712,) vs (3, 712)

How can I fill my newX NPArray with my x array from keys 1-2 but keep all keys at 0 the same?


回答1:


You may need adding values after the dataframe

newX[:, 1:] = x.values
newX
Out[171]: 
array([[0., 0., 0.],
       [0., 1., 0.],
       [0., 0., 0.],
       [0., 1., 1.],
       [0., 0., 0.]])


来源:https://stackoverflow.com/questions/54029900/how-to-fill-an-nparray-with-another-array-starting-at-a-key-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!