【时间】2018.12.03
【题目】numpy中的np.c_和np.r_详解
一维数组在numpy里面以列向量存储。。。。。。。。。。。。
一、np.c_和np.r_用于连接两个矩阵
np.r_中的r是row(行)的缩写,是按行叠加两个矩阵的意思,也可以说是按列连接两个矩阵,就是把两矩阵上下相加,要求列数相等,类似于pandas中的concat()。
np.c_中的c是column(列)的缩写,是按列叠加两个矩阵的意思,也可以说是按行连接两个矩阵,就是把两矩阵左右相加,要求行数相等,类似于pandas中的merge()。
二、示例说明
【代码】
-
import numpy
as np
-
-
a = np.array([
1,
2,
3]).reshape(
1,
3)
-
-
b = np.array([
4,
5,
6]).reshape(
1,
3)
-
-
print(a.shape,b.shape)
-
-
print(
"a=",a,
"b=",b)
-
-
c = np.c_[a,b]
-
-
print(
"np.c_[a,b]:\n",c)
-
-
print(c.shape)
-
-
d=np.r_[a,b]
-
-
print(
"np.r_[a,b]:\n",d)
-
-
print(d.shape)
【运行结果】:
【注意】若不使用reshape(1,3),则默认是列向量,虽然依旧以行向量的形式显示,如下:
【代码】
-
import numpy
as np
-
-
a = np.array([
1,
2,
3])
-
-
b = np.array([
4,
5,
6])
-
-
print(a.shape,b.shape)
-
-
print(
"a=",a,
"b=",b)
-
-
c = np.c_[a,b]
-
-
print(
"np.c_[a,b]:\n",c)
-
-
print(c.shape)
-
-
d=np.r_[a,b]
-
-
print(
"np.r_[a,b]:\n",d)
-
-
print(d.shape)
【运行结果】