w3resource

Pandas Data Series: Convert a given Series to an array

Pandas: Data Series Exercise-9 with Solution

Write a Pandas program to convert a given Series to an array.

Sample Solution :

Python Code :

import pandas as pd
import numpy as np
s1 = pd.Series(['100', '200', 'python', '300.12', '400'])
print("Original Data Series:")
print(s1)
print("Series to an array")
a = s1.values
print(a)
print(type(a))

Sample Output:

Original Data Series:
0       100
1       200
2    python
3    300.12
4       400
dtype: object
Series to an array
['100' '200' 'python' '300.12' '400']
<class 'numpy.ndarray'>                     

Explanation:

s1 = pd.Series(['100', '200', 'python', '300.12', '400']): This code creates a Pandas Series object 's1' containing a sequence of five string values: ['100', '200', 'python', '300.12', '400'].

a = np.array(s1.values.tolist()): This code extracts the values of the Pandas Series object 's1' using the .values attribute and assigns them to a new variable 'a'.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python Pandas program to convert the first column of a DataFrame as a Series.
Next: Write a Pandas program to convert Series of lists to one Series.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://198.211.115.131/python-exercises/pandas/python-pandas-data-series-exercise-9.php