Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2Functions in the ``as*array`` family that promote array-likes into arrays. 

3 

4`require` fits this category despite its name not matching this pattern. 

5""" 

6from .overrides import set_module 

7from .multiarray import array 

8 

9 

10__all__ = [ 

11 "asarray", "asanyarray", "ascontiguousarray", "asfortranarray", "require", 

12] 

13 

14@set_module('numpy') 

15def asarray(a, dtype=None, order=None): 

16 """Convert the input to an array. 

17 

18 Parameters 

19 ---------- 

20 a : array_like 

21 Input data, in any form that can be converted to an array. This 

22 includes lists, lists of tuples, tuples, tuples of tuples, tuples 

23 of lists and ndarrays. 

24 dtype : data-type, optional 

25 By default, the data-type is inferred from the input data. 

26 order : {'C', 'F'}, optional 

27 Whether to use row-major (C-style) or 

28 column-major (Fortran-style) memory representation. 

29 Defaults to 'C'. 

30 

31 Returns 

32 ------- 

33 out : ndarray 

34 Array interpretation of `a`. No copy is performed if the input 

35 is already an ndarray with matching dtype and order. If `a` is a 

36 subclass of ndarray, a base class ndarray is returned. 

37 

38 See Also 

39 -------- 

40 asanyarray : Similar function which passes through subclasses. 

41 ascontiguousarray : Convert input to a contiguous array. 

42 asfarray : Convert input to a floating point ndarray. 

43 asfortranarray : Convert input to an ndarray with column-major 

44 memory order. 

45 asarray_chkfinite : Similar function which checks input for NaNs and Infs. 

46 fromiter : Create an array from an iterator. 

47 fromfunction : Construct an array by executing a function on grid 

48 positions. 

49 

50 Examples 

51 -------- 

52 Convert a list into an array: 

53 

54 >>> a = [1, 2] 

55 >>> np.asarray(a) 

56 array([1, 2]) 

57 

58 Existing arrays are not copied: 

59 

60 >>> a = np.array([1, 2]) 

61 >>> np.asarray(a) is a 

62 True 

63 

64 If `dtype` is set, array is copied only if dtype does not match: 

65 

66 >>> a = np.array([1, 2], dtype=np.float32) 

67 >>> np.asarray(a, dtype=np.float32) is a 

68 True 

69 >>> np.asarray(a, dtype=np.float64) is a 

70 False 

71 

72 Contrary to `asanyarray`, ndarray subclasses are not passed through: 

73 

74 >>> issubclass(np.recarray, np.ndarray) 

75 True 

76 >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray) 

77 >>> np.asarray(a) is a 

78 False 

79 >>> np.asanyarray(a) is a 

80 True 

81 

82 """ 

83 return array(a, dtype, copy=False, order=order) 

84 

85 

86@set_module('numpy') 

87def asanyarray(a, dtype=None, order=None): 

88 """Convert the input to an ndarray, but pass ndarray subclasses through. 

89 

90 Parameters 

91 ---------- 

92 a : array_like 

93 Input data, in any form that can be converted to an array. This 

94 includes scalars, lists, lists of tuples, tuples, tuples of tuples, 

95 tuples of lists, and ndarrays. 

96 dtype : data-type, optional 

97 By default, the data-type is inferred from the input data. 

98 order : {'C', 'F'}, optional 

99 Whether to use row-major (C-style) or column-major 

100 (Fortran-style) memory representation. Defaults to 'C'. 

101 

102 Returns 

103 ------- 

104 out : ndarray or an ndarray subclass 

105 Array interpretation of `a`. If `a` is an ndarray or a subclass 

106 of ndarray, it is returned as-is and no copy is performed. 

107 

108 See Also 

109 -------- 

110 asarray : Similar function which always returns ndarrays. 

111 ascontiguousarray : Convert input to a contiguous array. 

112 asfarray : Convert input to a floating point ndarray. 

113 asfortranarray : Convert input to an ndarray with column-major 

114 memory order. 

115 asarray_chkfinite : Similar function which checks input for NaNs and 

116 Infs. 

117 fromiter : Create an array from an iterator. 

118 fromfunction : Construct an array by executing a function on grid 

119 positions. 

120 

121 Examples 

122 -------- 

123 Convert a list into an array: 

124 

125 >>> a = [1, 2] 

126 >>> np.asanyarray(a) 

127 array([1, 2]) 

128 

129 Instances of `ndarray` subclasses are passed through as-is: 

130 

131 >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray) 

132 >>> np.asanyarray(a) is a 

133 True 

134 

135 """ 

136 return array(a, dtype, copy=False, order=order, subok=True) 

137 

138 

139@set_module('numpy') 

140def ascontiguousarray(a, dtype=None): 

141 """ 

142 Return a contiguous array (ndim >= 1) in memory (C order). 

143 

144 Parameters 

145 ---------- 

146 a : array_like 

147 Input array. 

148 dtype : str or dtype object, optional 

149 Data-type of returned array. 

150 

151 Returns 

152 ------- 

153 out : ndarray 

154 Contiguous array of same shape and content as `a`, with type `dtype` 

155 if specified. 

156 

157 See Also 

158 -------- 

159 asfortranarray : Convert input to an ndarray with column-major 

160 memory order. 

161 require : Return an ndarray that satisfies requirements. 

162 ndarray.flags : Information about the memory layout of the array. 

163 

164 Examples 

165 -------- 

166 >>> x = np.arange(6).reshape(2,3) 

167 >>> np.ascontiguousarray(x, dtype=np.float32) 

168 array([[0., 1., 2.], 

169 [3., 4., 5.]], dtype=float32) 

170 >>> x.flags['C_CONTIGUOUS'] 

171 True 

172 

173 Note: This function returns an array with at least one-dimension (1-d)  

174 so it will not preserve 0-d arrays.  

175 

176 """ 

177 return array(a, dtype, copy=False, order='C', ndmin=1) 

178 

179 

180@set_module('numpy') 

181def asfortranarray(a, dtype=None): 

182 """ 

183 Return an array (ndim >= 1) laid out in Fortran order in memory. 

184 

185 Parameters 

186 ---------- 

187 a : array_like 

188 Input array. 

189 dtype : str or dtype object, optional 

190 By default, the data-type is inferred from the input data. 

191 

192 Returns 

193 ------- 

194 out : ndarray 

195 The input `a` in Fortran, or column-major, order. 

196 

197 See Also 

198 -------- 

199 ascontiguousarray : Convert input to a contiguous (C order) array. 

200 asanyarray : Convert input to an ndarray with either row or 

201 column-major memory order. 

202 require : Return an ndarray that satisfies requirements. 

203 ndarray.flags : Information about the memory layout of the array. 

204 

205 Examples 

206 -------- 

207 >>> x = np.arange(6).reshape(2,3) 

208 >>> y = np.asfortranarray(x) 

209 >>> x.flags['F_CONTIGUOUS'] 

210 False 

211 >>> y.flags['F_CONTIGUOUS'] 

212 True 

213 

214 Note: This function returns an array with at least one-dimension (1-d)  

215 so it will not preserve 0-d arrays.  

216 

217 """ 

218 return array(a, dtype, copy=False, order='F', ndmin=1) 

219 

220 

221@set_module('numpy') 

222def require(a, dtype=None, requirements=None): 

223 """ 

224 Return an ndarray of the provided type that satisfies requirements. 

225 

226 This function is useful to be sure that an array with the correct flags 

227 is returned for passing to compiled code (perhaps through ctypes). 

228 

229 Parameters 

230 ---------- 

231 a : array_like 

232 The object to be converted to a type-and-requirement-satisfying array. 

233 dtype : data-type 

234 The required data-type. If None preserve the current dtype. If your 

235 application requires the data to be in native byteorder, include 

236 a byteorder specification as a part of the dtype specification. 

237 requirements : str or list of str 

238 The requirements list can be any of the following 

239 

240 * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array 

241 * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array 

242 * 'ALIGNED' ('A') - ensure a data-type aligned array 

243 * 'WRITEABLE' ('W') - ensure a writable array 

244 * 'OWNDATA' ('O') - ensure an array that owns its own data 

245 * 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass 

246 

247 Returns 

248 ------- 

249 out : ndarray 

250 Array with specified requirements and type if given. 

251 

252 See Also 

253 -------- 

254 asarray : Convert input to an ndarray. 

255 asanyarray : Convert to an ndarray, but pass through ndarray subclasses. 

256 ascontiguousarray : Convert input to a contiguous array. 

257 asfortranarray : Convert input to an ndarray with column-major 

258 memory order. 

259 ndarray.flags : Information about the memory layout of the array. 

260 

261 Notes 

262 ----- 

263 The returned array will be guaranteed to have the listed requirements 

264 by making a copy if needed. 

265 

266 Examples 

267 -------- 

268 >>> x = np.arange(6).reshape(2,3) 

269 >>> x.flags 

270 C_CONTIGUOUS : True 

271 F_CONTIGUOUS : False 

272 OWNDATA : False 

273 WRITEABLE : True 

274 ALIGNED : True 

275 WRITEBACKIFCOPY : False 

276 UPDATEIFCOPY : False 

277 

278 >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F']) 

279 >>> y.flags 

280 C_CONTIGUOUS : False 

281 F_CONTIGUOUS : True 

282 OWNDATA : True 

283 WRITEABLE : True 

284 ALIGNED : True 

285 WRITEBACKIFCOPY : False 

286 UPDATEIFCOPY : False 

287 

288 """ 

289 possible_flags = {'C': 'C', 'C_CONTIGUOUS': 'C', 'CONTIGUOUS': 'C', 

290 'F': 'F', 'F_CONTIGUOUS': 'F', 'FORTRAN': 'F', 

291 'A': 'A', 'ALIGNED': 'A', 

292 'W': 'W', 'WRITEABLE': 'W', 

293 'O': 'O', 'OWNDATA': 'O', 

294 'E': 'E', 'ENSUREARRAY': 'E'} 

295 if not requirements: 

296 return asanyarray(a, dtype=dtype) 

297 else: 

298 requirements = {possible_flags[x.upper()] for x in requirements} 

299 

300 if 'E' in requirements: 

301 requirements.remove('E') 

302 subok = False 

303 else: 

304 subok = True 

305 

306 order = 'A' 

307 if requirements >= {'C', 'F'}: 

308 raise ValueError('Cannot specify both "C" and "F" order') 

309 elif 'F' in requirements: 

310 order = 'F' 

311 requirements.remove('F') 

312 elif 'C' in requirements: 

313 order = 'C' 

314 requirements.remove('C') 

315 

316 arr = array(a, dtype=dtype, order=order, copy=False, subok=subok) 

317 

318 for prop in requirements: 

319 if not arr.flags[prop]: 

320 arr = arr.copy(order) 

321 break 

322 return arr