How to create a Pandas Series from lists, arrays, and dictionaries?

I recently learned about Pandas series objects in an online course. I learned that they are 1D array-like data structures capable of holding various data types, including integers, floats, strings, and other Python objects. One way to explain a series is that it resembles a column in a spreadsheet or a database table, with a labeled index.

I am curious to know if it is possible to create a series using other Python data structures like lists, dictionaries, and arrays. If so, can anyone provide me with some code snippets on how to do it? Additionally, it would be helpful if you could provide a brief description of each of these data structures.

1 Like

Yes, it is possible that you can create a series object using other Python data structures. Here is how you can create it using the list data structure:

A list is an ordered collection of elements that can be of different types, they are mutable, meaning that the elements can be modified after the list is created. You can create a list using square brackets [ ], with the elements separated by commas.

You can also use a list to create a custom index for your series object, the catch is that the length of the list containing the values must be equal to the length of the index list. Here’s how you can do it:

Hey @mubashir_rizvi, It’s good to know that you’re learning about Pandas. You can use a Python dictionary also to develop a series. Let me show you how you work with dictionaries below:

Food for thought :blush:
A dictionary is an unordered collection of key-value pairs. The keys in a dictionary must be unique and immutable (i.e. strings, numbers, or tuples that contain only immutable elements), and the values can be of any type. They are created using curly braces { }, with key-value pairs separated by a colon : and individual pairs separated by a comma.

I hope the above explanation helps you. Let me know if you have any confusion.

Hi @mubashir_rizvi, you can also use a NumPy array to achieve this task. An array is a grid of values, all of the same type, and is indexed by a tuple of positive integers. They are similar to Python lists but offer much more functionality, including the ability to perform mathematical operations on multiple elements simultaneously. Here is how you can create a series using arrays:

  • The arange() function in the NumPy library returns an array with evenly spaced values within a specified interval.
  • The step argument (3rd argument) in arange() function defines the spacing between two consecutive elements in the array. The default value is 1.