Use df.to_numpy()

It's better than df.values, here's why.*

It's time to deprecate your usage of values and as_matrix().

pandas v0.24.0 introduced two new methods for obtaining NumPy arrays from pandas objects:

  1. to_numpy(), which is defined on Index, Series, and DataFrame objects, and
  2. array, which is defined on Index and Series objects only.

If you visit the v0.24 docs for .values, you will see a big red warning that says:

Warning: We recommend using DataFrame.to_numpy() instead.

See this section of the v0.24.0 release notes, and this answer for more information.

* - to_numpy() is my recommended method for any production code that needs to run reliably for many versions into the future. However if you're just making a scratchpad in jupyter or the terminal, using .values to save a few milliseconds of typing is a permissable exception. You can always add the fit n finish later.



Towards Better Consistency: to_numpy()

In the spirit of better consistency throughout the API, a new method to_numpy has been introduced to extract the underlying NumPy array from DataFrames.

# Setup
df = pd.DataFrame(data={'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}, 
                  index=['a', 'b', 'c'])

# Convert the entire DataFrame
df.to_numpy()
# array([[1, 4, 7],
#        [2, 5, 8],
#        [3, 6, 9]])

# Convert specific columns
df[['A', 'C']].to_numpy()
# array([[1, 7],
#        [2, 8],
#        [3, 9]])

As mentioned above, this method is also defined on Index and Series objects (see here).

df.index.to_numpy()
# array(['a', 'b', 'c'], dtype=object)

df['A'].to_numpy()
#  array([1, 2, 3])

By default, a view is returned, so any modifications made will affect the original.

v = df.to_numpy()
v[0, 0] = -1
 
df
   A  B  C
a -1  4  7
b  2  5  8
c  3  6  9

If you need a copy instead, use to_numpy(copy=True).


pandas >= 1.0 update for ExtensionTypes

If you're using pandas 1.x, chances are you'll be dealing with extension types a lot more. You'll have to be a little more careful that these extension types are correctly converted.

a = pd.array([1, 2, None], dtype="Int64")                                  
a                                                                          

<IntegerArray>
[1, 2, <NA>]
Length: 3, dtype: Int64 

# Wrong
a.to_numpy()                                                               
# array([1, 2, <NA>], dtype=object)  # yuck, objects

# Correct
a.to_numpy(dtype='float', na_value=np.nan)                                 
# array([ 1.,  2., nan])

# Also correct
a.to_numpy(dtype='int', na_value=-1)
# array([ 1,  2, -1])

This is called out in the docs.


If you need the dtypes in the result...

As shown in another answer, DataFrame.to_records is a good way to do this.

df.to_records()
# rec.array([('a', 1, 4, 7), ('b', 2, 5, 8), ('c', 3, 6, 9)],
#           dtype=[('index', 'O'), ('A', '<i8'), ('B', '<i8'), ('C', '<i8')])

This cannot be done with to_numpy, unfortunately. However, as an alternative, you can use np.rec.fromrecords:

v = df.reset_index()
np.rec.fromrecords(v, names=v.columns.tolist())
# rec.array([('a', 1, 4, 7), ('b', 2, 5, 8), ('c', 3, 6, 9)],
#           dtype=[('index', '<U1'), ('A', '<i8'), ('B', '<i8'), ('C', '<i8')])

Performance wise, it's nearly the same (actually, using rec.fromrecords is a bit faster).

df2 = pd.concat([df] * 10000)

%timeit df2.to_records()
%%timeit
v = df2.reset_index()
np.rec.fromrecords(v, names=v.columns.tolist())

12.9 ms ± 511 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
9.56 ms ± 291 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


Rationale for Adding a New Method

to_numpy() (in addition to array) was added as a result of discussions under two GitHub issues GH19954 and GH23623.

Specifically, the docs mention the rationale:

[...] with .values it was unclear whether the returned value would be the actual array, some transformation of it, or one of pandas custom arrays (like Categorical). For example, with PeriodIndex, .values generates a new ndarray of period objects each time. [...]

to_numpy aims to improve the consistency of the API, which is a major step in the right direction. .values will not be deprecated in the current version, but I expect this may happen at some point in the future, so I would urge users to migrate towards the newer API, as soon as you can.



Critique of Other Solutions

DataFrame.values has inconsistent behaviour, as already noted.

DataFrame.get_values() was quietly removed in v1.0 and was previously deprecated in v0.25. Before that, it was simply a wrapper around DataFrame.values, so everything said above applies.

DataFrame.as_matrix() was removed in v1.0 and was previously deprecated in v0.23. Do NOT use!

Answer from coldspeed95 on Stack Overflow
Top answer
1 of 16
638

Use df.to_numpy()

It's better than df.values, here's why.*

It's time to deprecate your usage of values and as_matrix().

pandas v0.24.0 introduced two new methods for obtaining NumPy arrays from pandas objects:

  1. to_numpy(), which is defined on Index, Series, and DataFrame objects, and
  2. array, which is defined on Index and Series objects only.

If you visit the v0.24 docs for .values, you will see a big red warning that says:

Warning: We recommend using DataFrame.to_numpy() instead.

See this section of the v0.24.0 release notes, and this answer for more information.

* - to_numpy() is my recommended method for any production code that needs to run reliably for many versions into the future. However if you're just making a scratchpad in jupyter or the terminal, using .values to save a few milliseconds of typing is a permissable exception. You can always add the fit n finish later.



Towards Better Consistency: to_numpy()

In the spirit of better consistency throughout the API, a new method to_numpy has been introduced to extract the underlying NumPy array from DataFrames.

# Setup
df = pd.DataFrame(data={'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}, 
                  index=['a', 'b', 'c'])

# Convert the entire DataFrame
df.to_numpy()
# array([[1, 4, 7],
#        [2, 5, 8],
#        [3, 6, 9]])

# Convert specific columns
df[['A', 'C']].to_numpy()
# array([[1, 7],
#        [2, 8],
#        [3, 9]])

As mentioned above, this method is also defined on Index and Series objects (see here).

df.index.to_numpy()
# array(['a', 'b', 'c'], dtype=object)

df['A'].to_numpy()
#  array([1, 2, 3])

By default, a view is returned, so any modifications made will affect the original.

v = df.to_numpy()
v[0, 0] = -1
 
df
   A  B  C
a -1  4  7
b  2  5  8
c  3  6  9

If you need a copy instead, use to_numpy(copy=True).


pandas >= 1.0 update for ExtensionTypes

If you're using pandas 1.x, chances are you'll be dealing with extension types a lot more. You'll have to be a little more careful that these extension types are correctly converted.

a = pd.array([1, 2, None], dtype="Int64")                                  
a                                                                          

<IntegerArray>
[1, 2, <NA>]
Length: 3, dtype: Int64 

# Wrong
a.to_numpy()                                                               
# array([1, 2, <NA>], dtype=object)  # yuck, objects

# Correct
a.to_numpy(dtype='float', na_value=np.nan)                                 
# array([ 1.,  2., nan])

# Also correct
a.to_numpy(dtype='int', na_value=-1)
# array([ 1,  2, -1])

This is called out in the docs.


If you need the dtypes in the result...

As shown in another answer, DataFrame.to_records is a good way to do this.

df.to_records()
# rec.array([('a', 1, 4, 7), ('b', 2, 5, 8), ('c', 3, 6, 9)],
#           dtype=[('index', 'O'), ('A', '<i8'), ('B', '<i8'), ('C', '<i8')])

This cannot be done with to_numpy, unfortunately. However, as an alternative, you can use np.rec.fromrecords:

v = df.reset_index()
np.rec.fromrecords(v, names=v.columns.tolist())
# rec.array([('a', 1, 4, 7), ('b', 2, 5, 8), ('c', 3, 6, 9)],
#           dtype=[('index', '<U1'), ('A', '<i8'), ('B', '<i8'), ('C', '<i8')])

Performance wise, it's nearly the same (actually, using rec.fromrecords is a bit faster).

df2 = pd.concat([df] * 10000)

%timeit df2.to_records()
%%timeit
v = df2.reset_index()
np.rec.fromrecords(v, names=v.columns.tolist())

12.9 ms ± 511 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
9.56 ms ± 291 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


Rationale for Adding a New Method

to_numpy() (in addition to array) was added as a result of discussions under two GitHub issues GH19954 and GH23623.

Specifically, the docs mention the rationale:

[...] with .values it was unclear whether the returned value would be the actual array, some transformation of it, or one of pandas custom arrays (like Categorical). For example, with PeriodIndex, .values generates a new ndarray of period objects each time. [...]

to_numpy aims to improve the consistency of the API, which is a major step in the right direction. .values will not be deprecated in the current version, but I expect this may happen at some point in the future, so I would urge users to migrate towards the newer API, as soon as you can.



Critique of Other Solutions

DataFrame.values has inconsistent behaviour, as already noted.

DataFrame.get_values() was quietly removed in v1.0 and was previously deprecated in v0.25. Before that, it was simply a wrapper around DataFrame.values, so everything said above applies.

DataFrame.as_matrix() was removed in v1.0 and was previously deprecated in v0.23. Do NOT use!

2 of 16
464

To convert a pandas dataframe (df) to a numpy ndarray, use this code:

df.values

array([[nan, 0.2, nan],
       [nan, nan, 0.5],
       [nan, 0.2, 0.5],
       [0.1, 0.2, nan],
       [0.1, 0.2, 0.5],
       [0.1, nan, 0.5],
       [0.1, nan, nan]])

If a specific column is needed:

df['column'].values
People also ask

How to convert table to JSON in Python?
In Python, you can convert a table to JSON format by using the `pandas` library. Load the table data into a `pandas` DataFrame and then use the `to_json()` method to convert the DataFrame to JSON format. You can specify different options for the JSON conversion, such as orienting the JSON output as records, columns, or values.
🌐
docs.kanaries.net
docs.kanaries.net › topics › Pandas › pandas-dataframe-numpy-array
How to Convert Pandas Dataframe to Numpy Array – Kanaries
How to convert list to JSON in Python?
In Python, you can convert a list to JSON format using the `json.dumps()` function. Pass the list as an argument to `json.dumps()` and it will return a JSON-formatted string representation of the list. You can also specify additional options, such as indenting the JSON output for better readability.
🌐
docs.kanaries.net
docs.kanaries.net › topics › Pandas › pandas-dataframe-numpy-array
How to Convert Pandas Dataframe to Numpy Array – Kanaries
How to convert table data into JSON format?
To convert table data into JSON format, you can iterate over the rows of the table and create a dictionary for each row, where the keys are the column names and the values are the corresponding values in the row. You can then store these dictionaries in a list and use the `json.dumps()` function to convert the list to JSON format.
🌐
docs.kanaries.net
docs.kanaries.net › topics › Pandas › pandas-dataframe-numpy-array
How to Convert Pandas Dataframe to Numpy Array – Kanaries
🌐
GeeksforGeeks
geeksforgeeks.org › python › pandas-dataframe-to_numpy-convert-dataframe-to-numpy-array
Pandas Dataframe.to_numpy() - Convert dataframe to Numpy array - GeeksforGeeks
July 12, 2025 - Example 3: In this example, we convert the entire DataFrame to a NumPy array and explicitly set the data type to float32. This can help save memory or match data types required by other libraries. ... import pandas as pd df = pd.DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], columns=['a', 'b', 'c']) a = df.to_numpy(dtype='float32') print(a.dtype,a)
🌐
Python Examples
pythonexamples.org › convert-pandas-dataframe-to-numpy-array
Convert Pandas DataFrame to NumPy Array
To convert Pandas DataFrame to Numpy Array, use the to_numpy() method of DataFrame class. to_numpy() transforms this DataFrame and returns a Numpy ndarray.
🌐
DataCamp
datacamp.com › doc › numpy › pandas-dataframes
NumPy to Pandas DataFrames
Data Input/Output & Conversion is used when you need to switch between Pandas DataFrames and NumPy arrays for functionality that is unique to each library. This operation is crucial for data analysis tasks requiring efficient computation and flexible data manipulation. # Convert Pandas DataFrame to NumPy array numpy_array = dataframe.to_numpy() # Convert NumPy array to Pandas DataFrame dataframe = pd.DataFrame(numpy_array, columns=['col1', 'col2', ...])
🌐
Note.nkmk.me
note.nkmk.me › home › python › pandas
Convert between pandas DataFrame/Series and NumPy array | note.nkmk.me
January 24, 2024 - import pandas as pd import numpy as np print(pd.__version__) # 2.1.4 print(np.__version__) # 1.26.2 ... To convert a DataFrame or Series to a NumPy array (ndarray), use the to_numpy() method or the values attribute.
Find elsewhere
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › convert pandas dataframe to numpy array
Convert Pandas DataFrame to NumPy Array - Spark By {Examples}
June 12, 2025 - You can convert pandas DataFrame to NumPy array by using to_numpy(), to_records(), index(), and values() methods. In this article, I will explain how to
🌐
Kanaries
docs.kanaries.net › topics › Pandas › pandas-dataframe-numpy-array
How to Convert Pandas Dataframe to Numpy Array – Kanaries
August 17, 2023 - Convert the DataFrame to a NumPy array using the to_numpy() method: ... Once you've followed the above steps, you should have a NumPy array that contains the same data as your Pandas DataFrame.
🌐
w3resource
w3resource.com › python-exercises › numpy › convert-a-pandas-dataframe-to-a-numpy-array-and-back.php
Convert a Pandas DataFrame to a NumPy array and back
September 1, 2025 - Create Pandas DataFrame: Define a Pandas DataFrame with some example data. Convert DataFrame to NumPy Array: Use the to_numpy() method of the DataFrame to convert it into a NumPy array.
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 0.25.1 › reference › api › pandas.DataFrame.to_numpy.html
pandas.DataFrame.to_numpy — pandas 0.25.1 documentation
By default, the dtype of the returned array will be the common NumPy dtype of all types in the DataFrame. For example, if the dtypes are float16 and float32, the results dtype will be float32. This may require copying data and coercing values, which may be expensive. ... Similar method for Series. ... With heterogenous data, the lowest common type will have to be used. >>> df = pd.DataFrame({"A": [1, 2], "B": [3.0, 4.5]}) >>> df.to_numpy() array([[1.
🌐
AskPython
askpython.com › python-modules › numpy › pandas-dataframe-to-numpy-array
Converting Pandas DataFrame to Numpy Array [Step-By-Step] - AskPython
February 7, 2024 - So first, we will see the conversion of this tabular structure (pandas data frame) into a numpy array. We can do this by using dataframe.to_numpy() method. This will convert the given Pandas Dataframe to Numpy Array.
🌐
Towards Data Science
towardsdatascience.com › home › latest › how to convert pandas dataframe into numpy array
How To Convert Pandas DataFrame Into NumPy Array | Towards Data Science
January 21, 2025 - The first option we have when it comes to converting a pandas DataFrame into a NumPy array is [pandas.DataFrame.to_numpy()](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_numpy.html) method.
🌐
Favtutor
favtutor.com › articles › pandas-dataframe-to-numpy-array
Convert Pandas DataFrame to NumPy Array (with code)
January 3, 2024 - The simplest method to convert a Pandas DataFrame to a NumPy array is by using the to_numpy() method.
🌐
GeeksforGeeks
geeksforgeeks.org › numpy › how-to-convert-a-dataframe-column-to-numpy-array
How to Convert a Dataframe Column to Numpy Array - GeeksforGeeks
July 26, 2025 - The asarray() function in NumPy converts the input to an array. It can be applied to a Pandas Series to convert it into a NumPy array.
🌐
Appdividend
appdividend.com › converting-pandas-dataframe-to-numpy-array
How to Convert Pandas DataFrame to Numpy Array
November 16, 2025 - The easiest way to convert an entire Pandas DataFrame to a NumPy array is using the ‘.to_numpy()’ method.
🌐
Medium
medium.com › @amit25173 › 5-effective-steps-to-convert-pandas-to-numpy-affa928229d8
5 Effective Steps to Convert pandas to numpy | by Amit Yadav | Medium
April 12, 2025 - You’ll find that manipulating DataFrames (an essential pandas datatype) often requires converting them into numpy arrays for advanced numerical operations.
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas convert column to numpy array
Pandas Convert Column to Numpy Array - Spark By {Examples}
July 3, 2025 - We can convert the Pandas DataFrame column to a Numpy array by using to_numpy() and values() functions. Using the to_numpy() function we
🌐
IncludeHelp
includehelp.com › python › how-to-convert-pandas-dataframe-to-numpy-array.aspx
How to convert pandas DataFrame to NumPy array?
April 18, 2023 - To convert a Panda DataFrame to NumPy array, simply use the DataFrame.to_numpy() method which is called with the DataFrame that we want to convert and it returns a 2D NumPy array of the same size/dimensions.
🌐
ActiveState
activestate.com › resources › quick-reads › how-to-convert-pandas-to-numpy
Resources | ActiveState
Guides, research, and training on securing open source at scale. Blog posts, video walkthroughs, case studies, and free certification courses.