Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

python - 如何将列添加到numpy数组(How can I add a column to a numpy array)

How can I add a column containing only "1" to the beginning of a second numpy array.

(如何在第二个numpy数组的开头添加仅包含“ 1”的列。)

X = np.array([1, 2], [3, 4], [5, 6])

I want to have X become

(我想让X变成)

[[1,1,2], [1,3,4],[1,5,6]]
  ask by Moose translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • You can use the np.insert

    (您可以使用np.insert)

     new_x = np.insert(x, 0, 1, axis=1) 
  • You can use the np.append method to add your array at the right of a column of 1 values

    (您可以使用np.append方法将数组添加到1值的列的右侧)

     x = np.array([[1, 2], [3, 4], [5, 6]]) ones = np.array([[1]] * len(x)) new_x = np.append(ones, x, axis=1) 

Both will give you the expected result

(两者都会给你预期的结果)

[[1 1 2]
 [1 3 4]
 [1 5 6]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...