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:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: How to convert a 2D NumPy array to a nested Python list and print it?
Next: How to convert a NumPy array to a Pandas series and print it?
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/numpy/convert-a-pandas-series-to-a-numpy-array-and-print.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics