In this very short tutorial today we’ll learn how you can turn a Pandas Series to a Numpy Array in Python.
Step 1: Create a Pandas Series
We’ll use a simple Series made of air temperature observations:
# We'll first import Pandas and Numpy import pandas as pd import numpy as np # Creating the Pandas Series min_temp = pd.Series ([42.9, 38.9, 38.4, 42.9, 42.2])
Step 2: Series conversion to NumPy array
We’ll go over two different methods:
We are able to use the np.array method for the conversion:
Note: The Dtype parameter is optional and should be specified if you are interested to modify the default data type for the array, which will be determined by NumPy.
Using Pandas method to_numpy()
Starting with Pandas 0.24, the newly method to_numpy is available.
Note: your Pandas version can be determined by running the following command:
import pandas as pd pd.__version__
Using to_numpy is simple, and requires only the Pandas library and is overall faster.
Which will obviously return the following array:
array([42.9, 38.9, 38.4, 42.9, 42.2])
Convert Series to string arrays
You can use the object dtype to get an array of strings.
my_u_array = np.array(min_temp, dtype= object)
array([42.9, 38.9, 38.4, 42.9, 42.2], dtype=object)