Monday 4 September 2023

How to convert a single column DataFrame to Series in Pandas

'squeeze()' method convert a one-column data frame to series.

 

Example

country_dataset = {
    'countries' : ['India', 'China', 'Sri Lanka']
}

df = pd.DataFrame(country_dataset)
series = df.squeeze()

 

Above snippet gets the series from one-column DataFrame.

 

dataframe_to_series.py

import pandas as pd

country_dataset = {
    'countries' : ['India', 'China', 'Sri Lanka']
}

df = pd.DataFrame(country_dataset)
series = df.squeeze()

print('df : ')
print(df)
print('type of df : ', type(df))

print('\nseries :')
print(series)
print('type of series : ', type(series))

 

Output

df : 
   countries
0      India
1      China
2  Sri Lanka
type of df :  <class 'pandas.core.frame.DataFrame'>

series :
0        India
1        China
2    Sri Lanka
Name: countries, dtype: object
type of series :  <class 'pandas.core.series.Series'>

If the dataframe has index labels, then same are used as row labels in a series.

 

series_from_dataframe_index.py

import pandas as pd

country_dataset = {
    'countries' : ['India', 'China', 'Sri Lanka'],
    'capitals' : ['New Delhi', 'Beijing', 'Colombo, Sri Jayawardenepura Kotte']
}

df = pd.DataFrame(country_dataset)
df.set_index('countries', inplace=True)
series = df.squeeze()

print('df : ')
print(df)
print('type of df : ', type(df))

print('\nseries :')
print(series)
print('type of series : ', type(series))

Output

df : 
                                     capitals
countries                                    
India                               New Delhi
China                                 Beijing
Sri Lanka  Colombo, Sri Jayawardenepura Kotte
type of df :  <class 'pandas.core.frame.DataFrame'>

series :
countries
India                                 New Delhi
China                                   Beijing
Sri Lanka    Colombo, Sri Jayawardenepura Kotte
Name: capitals, dtype: object
type of series :  <class 'pandas.core.series.Series'>

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment