Dev*_*ark 18 python arrays numpy python-2.7
在numpy结果数组的维度中,运行时会有所不同.1d数组和具有1列的2d数组之间经常存在混淆.在一种情况下,我可以遍历列,在另一种情况下,我不能.
你如何优雅地解决这个问题?为了避免使用if语句检查维度来乱丢我的代码,我使用此函数:
def reshape_to_vect(ar):
if len(ar.shape) == 1:
return ar.reshape(ar.shape[0],1)
return ar
Run Code Online (Sandbox Code Playgroud)
然而,这感觉不优雅且昂贵.有更好的解决方案吗?
Div*_*kar 10
你可以做 -
ar.reshape(ar.shape[0],-1)
Run Code Online (Sandbox Code Playgroud)
第二个输入reshape:-1处理第二轴的元素数量.因此,对于2D输入案例,它没有变化.对于1D输入案例,它创建一个2D数组,其中所有元素都被"推"到第一个轴,因为 ar.shape[0]它是元素的总数.
样品运行
1D案例:
In [87]: ar
Out[87]: array([ 0.80203158, 0.25762844, 0.67039516, 0.31021513, 0.80701097])
In [88]: ar.reshape(ar.shape[0],-1)
Out[88]:
array([[ 0.80203158],
[ 0.25762844],
[ 0.67039516],
[ 0.31021513],
[ 0.80701097]])
Run Code Online (Sandbox Code Playgroud)
2D案例:
In [82]: ar
Out[82]:
array([[ 0.37684126, 0.16973899, 0.82157815, 0.38958523],
[ 0.39728524, 0.03952238, 0.04153052, 0.82009233],
[ 0.38748174, 0.51377738, 0.40365096, 0.74823535]])
In [83]: ar.reshape(ar.shape[0],-1)
Out[83]:
array([[ 0.37684126, 0.16973899, 0.82157815, 0.38958523],
[ 0.39728524, 0.03952238, 0.04153052, 0.82009233],
[ 0.38748174, 0.51377738, 0.40365096, 0.74823535]])
Run Code Online (Sandbox Code Playgroud)
为了避免首先需要重新整形,如果您使用列表或“运行”切片对行/列进行切片,您将得到一个具有一行/列的二维数组
import numpy as np
x = np.array(np.random.normal(size=(4,4)))
print x, '\n'
Result:
[[ 0.01360395 1.12130368 0.95429414 0.56827029]
[-0.66592215 1.04852182 0.20588886 0.37623406]
[ 0.9440652 0.69157556 0.8252977 -0.53993904]
[ 0.6437994 0.32704783 0.52523173 0.8320762 ]]
y = x[:,[0]]
print y, 'col vector \n'
Result:
[[ 0.01360395]
[-0.66592215]
[ 0.9440652 ]
[ 0.6437994 ]] col vector
y = x[[0],:]
print y, 'row vector \n'
Result:
[[ 0.01360395 1.12130368 0.95429414 0.56827029]] row vector
# Slice with "running" index on a column
y = x[:,0:1]
print y, '\n'
Result:
[[ 0.01360395]
[-0.66592215]
[ 0.9440652 ]
[ 0.6437994 ]]
Run Code Online (Sandbox Code Playgroud)
相反,如果您使用单个数字来选择行/列,则会产生一维数组,这是问题的根本原因:
y = x[:,0]
print y, '\n'
Result:
[ 0.01360395 -0.66592215 0.9440652 0.6437994 ]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29134 次 |
| 最近记录: |