# ndarray - Methods and Data Type

Once you have created an array, you can check its various attributes using the inbuilt functions. Some of these are described below:

### ndarray.ndim

Returns the number of array dimensions.

```
>>> a
array([[ 1., 2., 3.],
[ 4., 5., 6.]])
>>> a.ndim
2
>>> x = np.array([1, 2, 3])
>>> x.ndim
1
```

### ndarray.shape

Returns a tuple of array dimensions. It can also be used to "reshape" the array, as long as this would not require a change in the total number of elements.

```
>>> a.shape
(2, 3)
>>> x.shape
(3,)
>>> a.shape = (3,2)
>>> a
array([[ 1., 2.],
[ 3., 4.],
[ 5., 6.]])
```

### ndarray.size

Returns the number of elements in the array. This can also be calculated with `np.prod(a.shape)`

, i.e., the product of the array’s dimensions.

```
>>> a
array([[ 1., 2.],
[ 3., 4.],
[ 5., 6.]])
>>> a.size
6
>>> np.prod(a.shape)
6
```

### NumPy array: default types

NumPy types are typically numeric types such as integers and floats of different precisions.

```
>>> import numpy as np
>>> qty = np.array([5,7,4,10,16])
>>> qty.dtype
dtype('int32')
>>> price = np.array([5,8,12.7,89.6,12.9,5.4])
>>> price.dtype
dtype('float64')
>>>
```

There are also some other types:

NumPy type | Example |
---|---|

Int | `myarr = np.array( [1, 5, 0, 3 ] )` |

Float | `myarr = np.array( [1, 5, 0, 3.1] )` |

Complex | `myarr = np.array( [1+2j, 3+4j, 6+7j] )` |

Bool | `myarr = np.array( [True, False, True] )` |

String | `myarr = np.array( ['Jon', 'Georg', 'Jose'] )` |

### Casting Array Data Types

An array with one dtype can be converted or casted into another dtype using ndarray’s `astype`

method.

```
>>> import numpy as np
>>> qty = np.array([5,7,4,10,16])
>>> qty.dtype
dtype('int32')
>>> float_qty = qty.astype(np.float64)
>>> float_qty.dtype
dtype('float64')
>>>
```

Casting can be specifically useful if you have an array of strings representing numeric data (numbers in quotes).

```
>>> prices = np.array(['5.1','8.6','12.7','89.6','12.9','5.4'])
>>> prices
array(['5.1', '8.6', '12.7', '89.6', '12.9', '5.4'],
dtype='<U4')
>>> prices_num = prices.astype(float)
>>> prices_num
array([ 5.1, 8.6, 12.7, 89.6, 12.9, 5.4])
>>> prices_num.dtype
dtype('float64')
>>>
```

- Python Dictionaries
- Comparison Operators in Python
- Logical Operators in Python
- Conditional Statements in Python
- For Loop in Python
- While Loop in Python
- How to loop over python dictionaries and Numpy arrays
- What is NumPy in Python
- ndarray - Methods and Data Type
- NumPy - Methods to Create Arrays
- Python NumPy - Numerical Operations on Arrays
- Python NumPy - Indexing and Slicing Arrays

# R Programming Bundle: 25% OFF

**R Programming - Data Science for Finance Bundle**for just $29 $39.