Table of Contents
TogglePandas Series is a one-dimensional array-like object containing data of any type, such as integers, floats, and strings. Each data element is associated with an index label. In this tutorial, you will learn how to convert a Series into various formats using built-in Pandas methods.
Use to_list() to convert a Series into a native Python list.
import pandas as pd
# Create a Pandas Series
s = pd.Series([1, 2, 3])
# Convert Series to a Python list
result = s.to_list()
print("Output:", result)
print("Output Type:", type(result))
Output: [1, 2, 3]
Output Type: <class ‘list’>
Use to_numpy() to convert the Series into a NumPy array.
import pandas as pd
s = pd.Series([1, 2, 3])
result = s.to_numpy()
print("Output:", result)
print("Output Type:", type(result))
Output: [1 2 3]
Output Type: <class ‘numpy.ndarray’>
Use to_dict() to transform a Series into a Python dictionary.
import pandas as pd
s = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
result = s.to_dict()
print("Output:", result)
print("Output Type:", type(result))
Output: {‘a’: 1, ‘b’: 2, ‘c’: 3}
Output Type: <class ‘dict’>
Use to_frame() to convert a Series into a DataFrame. You can specify a column name using the name parameter.
import pandas as pd
s = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
result = s.to_frame(name='Numbers')
print("Output:\n", result)
print("Output Type:", type(result))
Output:
Numbers
a 1
b 2
c 3
Output Type: <class ‘pandas.core.frame.DataFrame’>
Use to_string() to convert the Series into a human-readable string representation.
import pandas as pd
s = pd.Series([1, 2, 3], index=['r1', 'r2', 'r3'])
result = s.to_string()
print("Output:", repr(result))
print("Output Type:", type(result))
Output: ‘r1 1\nr2 2\nr3 3’
Output Type: <class ‘str’>
