Series: 0 1 1 2 2 3 3 4 4 5 dtype: int64 Array: [1 2 3 4 5]
The program first prints the Series series1. After that, it uses the Series.to_numpy() function to convert the Series to a NumPy array. [1 2 3 4 5] is the NumPy array.
How to convert a pandas DataFrame to a NumPy array?
As discussed in one of our previous articles, the pandas DataFrame is a two-dimensional data structure. It is also a labeled data structure. Both the rows and the columns of a DataFrame can be labeled. If we do not provide any labels, then by default the labels start from 0.
In Python, we can use the DataFrame.to_numpy() function to convert a pandas DataFrame to a NumPy array. For example, we can use the following Python code to convert a DataFrame to a NumPy array.
import pandas
df = pandas.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print("DataFrame: \n", df)
array2 = df.to_numpy()
print("Array: \n", array2)
Here, we are first creating a DataFrame df. After that, we are using the DataFrame.to_numpy() function to convert the DataFrame into a NumPy array.
The output of the program will be:
DataFrame:
0 1 2 3
0 1 2 3 4
1 5 6 7 8
2 9 10 11 12
Array:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]








































0 Comments