我想在第一列的所有行中添加一列' 1&... 例如,之前:
9 8 4
3 4 5
3 2 1
后:
1 9 8 4
1 3 4 5
1 3 2 1
到目前为止我的代码:
import numpy as np
import pandas as pd
training = pd.read_csv('data.csv', header = None)
training
training.shape
输出= (300, 14)
将数据制作成矩阵:
trainingData = training.values
在所有行的第一列中插入1列的列
featureVector = np.insert(featureVector, 0, 1, axis=0)
当我打印变量featureVector时,我看不到1 ...我该怎么做或修复它?
答案 0 :(得分:1)
这对我有用:
array = training.values
np.concatenate(([np.ones(len(array))],array.T),axis=0).T
答案 1 :(得分:1)
使用numpy.insert()
例程:
import numpy as np
training = np.loadtxt('data.csv', dtype=int)
training = np.insert(training, 0, 1, axis=1)
print(training)
输出:
[[1 9 8 4]
[1 3 4 5]
[1 3 2 1]]
答案 2 :(得分:0)
您可以连接1列矩阵和training
:
>>> import numpy as np
>>> training = np.array([9, 8, 4, 3, 4, 5, 3, 2, 1]).reshape(3, 3)
>>> np.concatenate((np.ones((training.shape[1], training)), a), axis=1)
array([[ 1., 9., 8., 4.],
[ 1., 3., 4., 5.],
[ 1., 3., 2., 1.]])
axis=1
用于指定应添加列。否则:
>>> np.concatenate(([[1,1,1]], training), axis=0)
array([[1, 1, 1],
[9, 8, 4],
[3, 4, 5],
[3, 2, 1]])
您也可以使用column_stack
:
>>> np.column_stack((np.ones(training.shape[1]), training))
array([[ 1., 9., 8., 4.],
[ 1., 3., 4., 5.],
[ 1., 3., 2., 1.]])