Prepare values for NumPy-based computation
A numerical algorithm accepts ndarray input rather than a labeled DataFrame.
Pandas · Module
DataFrame.to_numpy converts a DataFrame’s values into a NumPy array without its index or column labels. It chooses a common dtype by default, while dtype, copy, and na_value provide explicit control.
Call this method on a DataFrame to obtain its values as a NumPy array without the index or column labels. Pandas chooses one common NumPy dtype unless you provide dtype; mixed or incompatible column types can require coercion, copying, or an object array.
DataFrame.to_numpy(dtype=None, copy=False, na_value=<no_default>)| Name | Type | Description |
|---|---|---|
dtype | str or numpy.dtype, optional | Dtype passed to numpy.asarray(); defaults to pandas' selected common dtype. |
copy | bool, default False | Whether to ensure the returned array is not a view on another array; defaults to False. |
na_value | Any, optional | Value used for missing values; its default depends on dtype and column dtypes. |
numpy.ndarray — the NumPy array representing the DataFrame values.
import pandas as pd
frame = pd.DataFrame({"a": [1, 2], "b": [3.0, 4.5]})
array = frame.to_numpy(dtype="float32", copy=True)
print(array)
print(array.dtype)This converts the frame's values to a NumPy array with an explicitly selected dtype and a requested copy.
A numerical algorithm accepts ndarray input rather than a labeled DataFrame.
A downstream API requires a specific array dtype.
Missing entries need a sentinel value in an exported array.
It returns a NumPy array containing the DataFrame values. Row and column labels are not included, and the result normally uses a common NumPy dtype for all columns.
Follow-up: What happens with mixed numeric types? Pandas selects a common type capable of representing them, such as float32 for float16 and float32 input.
dtype controls the dtype passed to numpy.asarray(). If it is omitted, pandas derives a common NumPy dtype from the DataFrame's column dtypes.
Follow-up: Why can dtype selection matter? Choosing a suitable dtype can avoid an unintended object array, while incompatible values may still require coercion.
copy defaults to False and avoids copying when possible, but it does not guarantee a view. Set copy=True when the returned array must not be a view on another array.
Follow-up: What additional control is available for missing values? The na_value argument specifies the value used to represent missing entries.
DataFrame.valuesSeries.to_numpyIndex.to_numpyDataFrame.iloc