文档描述
来自官方文档的叙述(这里只简单翻译一部分)
numpy.c_
numpy.c_ = <numpy.lib.index_tricks.CClass object>
Translates slice objects to concatenation along the second axis.
将要拼接的对象转换为沿第二轴的连接。
第二个轴即axis=1
This is short-hand for np.r_[’-1,2,0’, index expression], which is useful because of its common occurrence. In particular, arrays will be stacked along their last axis after being upgraded to at least 2-D with 1’s post-pended to the shape (column vectors made out of 1-D arrays).
关于python科学计算(pandas、numpy)中axis(轴)的理解
理解
作用是将多个矩阵左右拼接在一起,构成一个新矩阵。
实例:
#摘自文档
>>> np.c_[np.array([1,2,3]), np.array([4,5,6])]
array([[1, 4],
[2, 5],
[3, 6]])
>>> np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])]
array([[1, 2, 3, 0, 0, 4, 5, 6]])
我实际遇到的应用:
>>>import numpy as np
>>>from sklearn.datasets import fetch_california_housing
>>>housing=fetch_california_housing()
>>>print(housing)
{'data': array([[ 8.3252 , 41. , 6.98412698, ..., 2.55555556,
37.88 , -122.23 ],
[ 8.3014 , 21. , 6.23813708, ..., 2.10984183,
37.86 , -122.22 ],
[ 7.2574 , 52. , 8.28813559, ..., 2.80225989,
37.85 , -122.24 ],
...,
[ 1.7 , 17. , 5.20554273, ..., 2.3256351 ,
39.43 , -121.22 ],
[ 1.8672 , 18. , 5.32951289, ..., 2.12320917,
39.43 , -121.32 ],
[ 2.3886 , 16. , 5.25471698, ..., 2.61698113,
39.37 , -121.24 ]]), 'target': a
>>>m,n=housing.data.shape
>>>print(m,n)
20640 8
#np.ones((m,1))构造一个m行1列,数值全为1的矩阵
#np.c_(A,B)将A与B延第二个轴拼接在一起。
>>>housing_data_plus_bias=np.c_[np.ones((m,1)),housing.data]
>>>print(housing_data_plus_bias)
[[ 1. 8.3252 41. ... 2.55555556
37.88 -122.23 ]
[ 1. 8.3014 21. ... 2.10984183
37.86 -122.22 ]
[ 1. 7.2574 52. ... 2.80225989
37.85 -122.24 ]
...
[ 1. 1.7 17. ... 2.3256351
39.43 -121.22 ]
[ 1. 1.8672 18. ... 2.12320917
39.43 -121.32 ]
[ 1. 2.3886 16. ... 2.61698113
39.37 -121.24 ]]
可以看到,最左侧一列是矩阵np.ones((m,1))
,而其余列均为矩阵housing.data
OK!记录完毕