Pandas: Coerce a DataFrame into a Series

Last updated on September 2, 2022 Napoleon Loading... Post a comment

There might be occasions when you want to convert a Pandas data frame into a series. You can do so by using the squeeze() method.

If your data frame has only a single column, you can turn it into a series like so:

import pandas as pd

words = ['Dog', 'Cat', 'Crocodile', 'Dragon', 'Egle', 'KindaCode.com', 'Sow']
df = pd.DataFrame(words, columns=['Words'])

word_series = df.squeeze()
print(type(word_series))
print(word_series)

Output:

<class 'pandas.core.series.Series'>
0              Dog
1              Cat
2        Crocodile
3           Dragon
4             Egle
5    KindaCode.com
6              Sow
Name: Words, dtype: object

In case your data frame has multiple columns, you have to specify the column you want to convert to a series. Here’s an example:

import pandas as pd

cars = {
    'Brand': ['Honda Civic', 'Toyota Corolla', 'Ford Focus', 'Audi A4'],
    'Price': [22000, 25000, 27000, 35000]
}

df = pd.DataFrame(cars, columns = ['Brand', 'Price'])

brand_series = df['Brand'].squeeze();

print(type (brand_series))
print(brand_series)

Output:

<class 'pandas.core.series.Series'>
0       Honda Civic
1    Toyota Corolla
2        Ford Focus
3           Audi A4
Name: Brand, dtype: object

Further reading:

You can also check out our Machine Learning category page or Python category page for more tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like