1. Python 中 reshape
numpy.arange(n).reshape(a, b) # 依次生成 n 个自然数,并且以 a 行 b 列的数组形式显示
''' 常见的用法 '''
reshape(n, -1) # 转化成 n 行
reshape(-1, m) # 转化成 m 列
举个栗子~
import pandas as pd
import numpy as np
a = list(range(1, 11, 1))
b = np.arange(1, 21, 2)
print(a)
print(b)
import pandas as pd
import numpy as np
a = list(range(1, 11, 1))
b = np.arange(1, 21, 2)
a_reshape = np.array(a).reshape(2, -1) # list 要转成 numpy.array 类型的数据,才能使用 reshape() 方法!
b_reshape = b.reshape(2, -1)
print(a_reshape)
print(b_reshape)
2. Matlab 中的 reshape
a = 1 : 10;
>> a_reshape = reshape(a, 2, [])
Tips:
1. Python 中的 reshape 方法只能用于 numpy 的数据类型,list 类型的数据不适用。
2. Python 中的 reshape 优先按照行存新数据,Matlab 中的 reshape 优先按照列存新数据!
若想在 Python 中也使用类似于 Matlab 中的存数方式,那么可以使用 .T,同时要注意设置的行数和列数要互换。比如:如果要生成 m 行 n 列的新数组,那么可以使用 np.shape(n, m).T!
import pandas as pd
import numpy as np
b = np.arange(1, 21, 2)
b_reshape = b.reshape(2, -1)
b_reshape_new = b.reshape(-1, 2).T
print(b_reshape)
print(b_reshape_new)