Pandas – Create a Pandas Series from a list.

Spread the love

You have some data in a python list and you want to create a pandas series from it. For example you have some restaurant ratings in a list and want to convert it to a pandas series like this.

Solution –

Create the List –

First let’s create the list.

quality_ratings = ['Good', 'Very Good', 'Good', 'Excellent', 'Very Good']
quality_ratings

Create a Pandas Series from a list –

Now, to create the pandas series from this list, we have to pass this list to pd.Series constructor.

# create pandas series from a list
ratings = pd.Series(quality_ratings)
ratings

Add an index and name to the Pandas Series –

Now, Let’s say that you also want to add an index for these ratings like which rating is belong to which restaurant and also want to add a name to this series.

To add an index when creating a series, we use the index parameter and to add a name we use the name parameter of pd.Series.

ratings = pd.Series(quality_ratings, index=['A','B','C','D','E'], 
                    name='restaurant_ratings')
ratings

Create a Pandas Series from List of Lists –

You have a data in a list of lists format and want to convert it into a pandas series.

# list of lists
quality_ratings = [['Good'], ['Very Good'], ['Good'], ['Excellent'], ['Very Good']]

# convert to a pandas series
ratings = pd.Series(lst[0] for lst in quality_ratings)
ratings

Here, we are iterating through each of the list from outer list and selecting the value at index 0 using a list comprehension to create the series.

  1. Create Pandas DataFrame from Lists.
  2. Create Pandas DataFrame from dictionary.
  3. Convert a Pandas DataFrame to a Dictionary.

Rating: 1 out of 5.

Leave a Reply