4 Ways to Convert Pandas Series into Numpy Array

Converting Series

You all might already be familiar that Pandas has two main data structures i.e series and dataframe. In previous articles, we have already learned how to convert a data frame into a Numpy Array. So today, in this article, we are going to learn about how to convert a series into a Numpy Array in python.

What is a Pandas Series in Python?

Pandas series is a one-dimensional data structure Pandas that can accept multiple data types such as integers, objects, and float data types. The advantage of the Pandas series over the data frame is that it can store multiple data types. You can make a series in a variety of methods such as creating a series from lists, tuples, or dictionaries or by passing a scalar value.

In this article, we will be making a series from dictionaries in python. We will use this series in the rest of the article too.

import pandas as pd

list = ['a', 'b', 'c', 'd', 'e']
  
my_series = pd.Series(list)
print(my_series)

Output:

0  a
1  b
2  c
3  d
4  e

What is a Numpy Array in Python?

A NumPy array is a data structure that accepts data of similar types only. Numpy arrays are almost like lists but don’t get confused. Arrays are more efficient than lists and also much more compact.

Let’s see how to create a NumPy array.

import numpy as np

my_arr = np.array([1, 2, 3, 4, 5])

print(my_arr)

Output:

[1 2 3 4 5]

Methods to Convert Pandas Series to Numpy Array

Now we will learn about some of the methods on how we can convert a Pandas series into a NumPy array using some of the functions and properties.

1. Using the Pandas.index.to_numpy() function

This is a fairly straightforward method, as it directly converts the elements inside a series into a NumPy array. We will first create a series with the pd.DataFrame() function and then convert it to a Numpy array.

For example,

import pandas as pd

df = pd.DataFrame({'A1': [1, 2, 3], 'A2': [4, 5, 6]}, index=['a', 'b', 'c']); 

array = df.index.to_numpy()
print(array)

Output:

['a' , 'b' , 'c']

2. Using the pandas.index.values property

In this method, we will convert the series into two steps. First, we will use pandas. index.values property This property will return the values at the index in the form of an array. This array will be converted into a NumPy array with the help of the NumPy.array function.

import pandas as pd
import numpy as np

df = pd.DataFrame({'A1': [1, 2, 3], 'A2': [4, 5, 6]}, index=['a', 'b', 'c']); 

array = np.array(df.index.values)
print(array)

Output:

['a' , 'b', 'c']

3. Using the pandas.index.array property

This property also works in two steps. First, it converts the pandas series into a Pandas array. Then the Pandas array is converted to a Numpy array with the help of numpy.array() function.

import pandas as pd
import numpy as np

df = pd.DataFrame({'A1': [1, 2, 3], 'A2': [4, 5, 6]}, index=['a', 'b', 'c']); 

array = np.array(df.index.array)
print(array)

Output:

['a' , 'b' , 'c']

4. Using the Pandas series.to_numpy() function

With this function, we will use a dataset, and we will first create a series from one of the columns in the dataset and then convert it into a Numpy array. In this, we have created a series first from the Movie Info column. Then we used the series.to_numpy() function to create a numpy array.

import pandas as pd 
  
data = pd.read_csv("/content/Highest Holywood Grossing Movies.csv") 
     
data.dropna(inplace = True)
 
my_ser = pd.Series(data['Movie Info'].head())
  
# using to_numpy() function
print((my_ser.to_numpy()))

Output:

['As a new threat to the galaxy rises, Rey, a desert scavenger, and Finn, an ex-stormtrooper, must join Han Solo and Chewbacca to search for the one hope of restoring peace.'
 "After the devastating events of Avengers: Infinity War, the universe is in ruins. With the help of remaining allies, the Avengers assemble once more in order to reverse Thanos' actions and restore balance to the universe."
 'A paraplegic Marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.'
 'A seventeen-year-old aristocrat falls in love with a kind but poor artist aboard the luxurious, ill-fated R.M.S. Titanic.'
 'A new theme park, built on the original site of Jurassic Park, creates a genetically modified hybrid dinosaur, the Indominus Rex, which escapes containment and goes on a killing spree.']

Conclusion

In this article, we learned a lot about the different methods we can use for converting a series into a Numpy array. Some methods do this in two steps while the other methods do this in one step.