Skip to main content
Documents
basicsArray CreationArray OperationsArray Computation & AnalysisLinear AlgebraRandom ProbabilityData Input/Output & Conversion

NumPy ones()

The NumPy `ones()` function is used to create an array filled with ones. It is commonly utilized in initializing arrays for various mathematical operations or as placeholders in algorithms.

Usage

The `ones()` function is used when you need an array of a specific shape filled with the value `1`. It is particularly useful in mathematical computations where initial values of one are required.

numpy.ones(shape, dtype=None, order='C')
  • `shape`: Defines the dimensions of the array (e.g., `(2, 3)` for a 2x3 array).
  • `dtype`: (Optional) Specifies the desired data type of the array elements, like `int` or `float`. The default is `float`.
  • `order`: (Optional) Determines the memory layout order, with 'C' for row-major and 'F' for column-major.

Examples

1. Basic 1D Array

import numpy as np

array = np.ones(5)

This creates a one-dimensional array of length 5 filled with ones.

2. 2D Array with Specified Data Type

import numpy as np

array = np.ones((2, 3), dtype=int)

Here, a 2x3 array of integers filled with ones is created, specifying the `dtype` as `int`.

3. Multi-dimensional Array with Memory Order

import numpy as np

array = np.ones((3, 4, 2), order='F')

This example generates a 3x4x2 array filled with ones, using column-major order for memory layout.

4. Using `ones_like`

import numpy as np

existing_array = np.array([[1, 2], [3, 4]])
array = np.ones_like(existing_array)

This creates an array of ones with the same shape and type as the `existing_array`.

Tips and Best Practices

  • Specify the `dtype`: Use `dtype` to ensure compatibility with other numerical operations, especially when precision is crucial.
  • Choose the right `order`: Select an appropriate memory order (`'C'` or `'F'`) based on the subsequent operations. The correct memory order can significantly impact performance due to cache efficiency.
  • Use `ones_like` for similar arrays: To create an array of ones with the same shape and type as an existing array, consider using `numpy.ones_like`.
  • Avoid unnecessary large arrays: Be mindful of memory usage when dealing with large arrays, as they can consume significant resources.