Skip to main content
v2026.11,986 entries · CC-BY 4.0

NumPy ones: Syntax, Shape and Research Examples

Create arrays of ones with explicit dimensions and dtype, then build and check a synthetic research design matrix.

Written and maintained by CASRAI Editorial Board

Published

On this page

NumPy ones creates a new array filled with 1, using the shape and data type you specify. Call np.ones((rows, columns)) for a two-dimensional array; this guide follows that construction into a research design matrix and checks the dimensions before fitting a model.

What it is used for in research

An array of ones provides a known starting value for numerical work. A concrete research use is the constant column in a linear-model design matrix: multiplying that column by its coefficient contributes the same intercept to each observation. NumPy’s linalg.lstsq documentation demonstrates a line fit using a column of ones alongside a predictor.

The array is a computational ingredient, rather than a set of measured observations. In the illustrative example below, the measured-variable positions contain explicitly synthetic values. The constant column simply encodes the chosen model. Creating it does not fit the model, estimate uncertainty or establish that the model is suitable for real data.

Keep the input task distinct from initialization. If measurements already exist in a Python list, creating a NumPy array from a list preserves those supplied values. Calling ones creates specified dimensions containing a repeated value instead. This distinction helps catch an accidental replacement of data with a placeholder.

Install or access

NumPy’s official installation page gives pip install numpy and conda install numpy as installation commands. Use the command appropriate to your existing project environment. The page recommends a virtual environment for dependency management; Python itself is the prerequisite.

pip install numpy

After installation, run the documented import and version check inside the Python session that will execute your analysis:

import numpy as np
print(np.__version__)

The np prefix is an import convention. It makes np.ones refer to NumPy’s function without writing the library’s full name on every call. If the import fails, resolve access to NumPy in that environment before debugging an array expression. Recording the printed version with an analysis also identifies which documentation applies to version-dependent arguments.

NumPy ones syntax and arguments

np.ones(shape, dtype=None, order='C', *, device=None, like=None)

Supply the required shape as an integer or a sequence of integers. The remaining arguments control representation or interoperability. The asterisk in the documented signature marks the following arguments as keyword-only; it is not something to copy into a call.

  • shape: np.ones(6) makes a vector. np.ones((6, 1)) makes six rows and one column. Put multiple dimensions together in one tuple.
  • dtype: the default is np.float64. Request a specific integer or floating type when the receiving calculation requires it, for example dtype=np.int16.
  • order: 'C' stores multidimensional data in row-major order; 'F' selects column-major order. Changing storage order does not exchange the row and column dimensions.
  • device: this interoperability parameter was added in NumPy 2.0.0. If supplied, its supported value is 'cpu'.
  • like: a compatible reference object can control creation through the __array_function__ protocol. This parameter was added in 1.20.0.

For routine NumPy construction, start with shape and an explicit dtype where needed. Leave interoperability arguments out unless your workflow actually needs them. In particular, like= is not a request to copy a reference array’s dimensions and type; that is the usual role of ones_like.

Step-by-step task: build a research design matrix

This illustrative composite uses four synthetic predictor values and four synthetic responses. It adapts the constant-column construction shown in the official least-squares example, using column_stack to make the column order explicit. It is a reproducible programming example, not evidence from a study.

  1. Create the synthetic input arrays. Enter x = np.array([0., 1., 2., 3.]) and y = np.array([2., 5., 8., 11.]). Each position represents one illustrative observation.
  2. Create one constant per observation. Enter intercept = np.ones(x.shape, dtype=np.float64). Here x.shape is (4,), so the result is a four-element vector.
  3. Assemble the design matrix. Enter X = np.column_stack((intercept, x)). The official column_stack reference specifies that one-dimensional inputs become columns and must have matching first dimensions.
  4. Inspect before solving. Print X and X.shape. The expected shape is (4, 2): four observations, with the constant first and predictor second.
  5. Fit and inspect the returned values. Call np.linalg.lstsq(X, y, rcond=None) and unpack its four outputs as below.
import numpy as np

x = np.array([0., 1., 2., 3.])
y = np.array([2., 5., 8., 11.])
intercept = np.ones(x.shape, dtype=np.float64)
X = np.column_stack((intercept, x))

print(X)
print(X.shape)
coef, residuals, rank, singular_values = np.linalg.lstsq(X, y, rcond=None)
print(coef)
print(rank)

The assembled matrix is:

[[1. 0.]
 [1. 1.]
 [1. 2.]
 [1. 3.]]

Its first column contributes the intercept, while the second contributes the predictor term. Because this example deliberately sets each response to 2 plus 3 times its predictor, the fitted coefficients are approximately [2., 3.]. Floating-point roundoff can affect the displayed final digits. Reversing the input column order reverses the interpretation of the coefficient positions.

The constant vector is sized from the predictor rather than from a separately typed observation count. As an editorial check for an analysis script, inspect both input lengths before assembly and preserve the pairing of each predictor with its response. Equal lengths alone cannot establish that two independently sorted arrays still describe the same observations.

Output and how to read it

Read an initialized array’s dimensions and type alongside its printed values. NumPy’s beginner guide defines shape as the lengths along each axis, ndim as the number of dimensions, size as the total element count and dtype as its element type. These are separate properties.

a = np.ones((3, 2), dtype=np.int16)
print(a.shape, a.ndim, a.size, a.dtype)
# (3, 2) 2 6 int16

In this check, the two shape entries mean two axes; they do not mean two elements. Multiplying three rows by two columns gives six stored entries. A printed decimal point in a default ones result indicates a floating representation, even though its numerical value is one. The downloadable data table below provides additional computed construction checks, including vectors and explicit row and column arrays.

Read orientation from shape

Specify the axes the next operation expects. A one-dimensional result has no separate row axis and column axis: its shape records only its length. A two-dimensional row records one row followed by its column count; a two-dimensional column records its row count followed by one column. Although all three arrangements can contain the same number of ones, their shapes describe different inputs to subsequent operations.

This is why the design-matrix example uses column_stack deliberately. That function turns one-dimensional inputs into columns, so the construction does not depend on treating a printed horizontal vector as an existing row matrix. The shape check belongs after assembly as well as before it: it confirms that the chosen combination produced one row per synthetic observation.

The solver’s output has a different meaning from the initialized array. In the worked task, coef contains two estimated coefficients in design-column order, residuals contains sums of squared residuals, rank is the rank of the design matrix and singular_values contains its singular values. The example’s rank is two. The NumPy norm and least-squares guide explains the adjacent linear-algebra operations.

Do not read an empty residual array as proof of a perfect fit. The official solver reference says that array is empty when the matrix rank is less than its column count, or when the row count is no greater than the column count. Inspect matrix dimensions and rank when interpreting that output.

Troubleshooting

Two dimensions passed as separate arguments

Use np.ones((3, 2)), not np.ones(3, 2). In the latter expression, the second positional argument occupies the dtype position rather than specifying columns. The tuple is what makes the pair a single shape argument. Check the call structure before changing numerical values elsewhere in a script.

A vector behaves differently from a column

A vector with shape (4,) is different from a two-dimensional column with shape (4, 1). NumPy compares dimensions from the right during broadcasting; corresponding lengths must be equal or one must be 1. Consequently, an operation can succeed while producing an unexpectedly large output.

column = np.ones((4, 1))
vector = np.array([2., 3., 4., 5.])
print((column * vector).shape)
# (4, 4)
print((column * vector[:, np.newaxis]).shape)
# (4, 1)

The first result contains every column-vector combination. The second explicitly aligns the four values down a column. Choose the orientation that expresses the intended operation, then inspect the resulting shape. The element-wise multiplication guide develops this distinction for array products.

The dtype did not follow an existing array

Use np.ones_like(reference) when the desired default is the reference’s shape and dtype. Plain np.ones(reference.shape) still uses its own default dtype. An explicit dtype overrides inheritance in ones_like:

reference = np.array([[2, 4], [6, 8]], dtype=np.int16)
same_type = np.ones_like(reference)
floating = np.ones_like(reference, dtype=np.float32)
print(same_type.dtype, floating.dtype)
# int16 float32

The related function also defaults to order='K', which attempts to follow the reference’s layout, and subok=True, which permits its subclass type. Those defaults differ from specifying only a fresh shape with ones.

A keyword is unavailable in an older environment

Compare np.__version__ with the documented introduction of an argument. The device argument requires NumPy 2.0.0 or later; like requires 1.20.0 or later. A newer online signature can therefore include arguments absent from an older analysis environment. For the ordinary array construction shown here, neither argument is needed.

An unnecessary full array is being allocated

If a formula only needs a scalar operation, consider expressing it directly. NumPy’s broadcasting documentation explains that scalar multiplication does not need a physically repeated scalar input. For a small illustrative array, values * 1 supplies the scalar without first constructing a matching ones array. Whether the resulting calculation is needed at all is a separate question.

When a genuine initialized array is required, choose the dimensions deliberately. Broadcasting can also create an output larger than either input, as the column/vector example shows. Avoid treating a short expression as evidence that it has a small memory footprint.

Free alternatives

Within the same open-source NumPy library, related constructors express different initialization tasks. The official array-creation reference documents the choices below. They are alternatives for the required starting values, rather than interchangeable replacements in every calculation.

Function Documented result Appropriate construction task
np.zeros New array filled with zero The intended initial value is zero.
np.full New array filled with a supplied value The intended repeated value is supplied explicitly.
np.empty New array without initialized entries Every required entry will be assigned before it is read.
np.eye Two-dimensional array with diagonal ones and zeros elsewhere The required pattern is diagonal rather than all ones.

The NumPy full guide covers supplied fill values in more detail. For empty, the initial contents are not a meaningful default: NumPy’s beginner guide explicitly warns to fill every element afterwards. Use a constructor that states the intended initial condition, and verify the result before passing it into a model or a saved research output.

Sources

Data: NumPy ones: computed shape and dtype checks

Reproducible synthetic construction checks compiled from the official NumPy ones, ones_like and array-attribute documentation. The reference for the last row has shape (2, 3) and dtype int16. Each row was computed with NumPy 2.5.4; these are programming examples, not measured research observations.

NumPy ones: computed shape and dtype checks
CallOutput shapeDimensionsElementsOutput dtype
np.ones(4)(4,)14float64
np.ones((4, 1))(4, 1)24float64
np.ones((1, 4))(1, 4)24float64
np.ones((2, 3), dtype=np.int16)(2, 3)26int16
np.ones_like(reference, dtype=np.float32)(2, 3)26float32

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about NumPy ones: Syntax, Shape and Research Examples

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →