Sometimes we may want to convert a pandas Series or DataFrame to a NumPy array and then, perform advanced mathematical operations. In this article, we will discuss:
- How to convert a pandas Series to a NumPy array?
- How to convert a pandas DataFrame to a NumPy array?
How to convert a pandas Series to a NumPy array?
As we discussed in our previous article, a pandas Series is a one-dimensional data structure. It is similar to NumPy one-dimensional array or Python list. But, the main difference is it is labeled. If we do not provide any labels, then by default the labels start from 0. For example, given below is an example of a pandas Series.
First 1 Second 2 Third 3 Fourth 4 Fifth 5 dtype: int64
The Series has five integers 1, 2, 3, 4, and 5. And the Series is a labeled data structure. So, First, Second, Third, Fourth, and Fifth are the labels.
In Python, we can use the Series.to_numpy() function to convert a Series to a NumPy array.
import pandas series1 = pandas.Series([1, 2, 3, 4, 5]) print(“Series: \n”, series1) array1 = series1.to_numpy() print(”Array: \n”, array1)
The output of the above program will be:
0 Comments