How to convert a Pandas series to a NumPy array and print it?
NumPy: Interoperability Exercise-11 with Solution
Write a NumPy program to convert a Pandas Series to a NumPy array and print the array.
Sample Solution:
Python Code:
import pandas as pd
import numpy as np
# Create a Pandas Series
series = pd.Series([10, 20, 30, 40, 50])
print("Original Pandas Series:",series)
print("Type:",type(series))
# Convert the Pandas Series to a NumPy array
array = series.to_numpy()
print("\nPandas Series to a NumPy array:")
# Print the NumPy array
print(array)
print("Type:",type(array))
Output:
Original Pandas Series: 0 10 1 20 2 30 3 40 4 50 dtype: int64 Type: <class 'pandas.core.series.Series'> Pandas Series to a NumPy array: [10 20 30 40 50] Type: <class 'numpy.ndarray'>
Explanation:
- Import Pandas and NumPy Libraries: Import the Pandas and NumPy libraries to work with Series and arrays.
- Create Pandas Series: Define a Pandas Series with some example data.
- Convert to NumPy Array: Use the to_numpy() method of the Pandas Series to convert it into a NumPy array.
- Print NumPy Array: Output the resulting NumPy array to verify the conversion.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics