Creating Series from list, dictionary, and numpy array in Pandas

Creating Series from list, dictionary, and numpy array in Pandas

Pandas provides a versatile and powerful data structure called Series. A Series is a one-dimensional labeled array that can hold data of any type. Here's how to create a Series object from various sources:

1. Import Pandas:

Before we start, ensure you have the Pandas library imported:

import pandas as pd 

2. Create a Series from a List:

data_list = [1, 2, 3, 4, 5] series_from_list = pd.Series(data_list) print(series_from_list) 

Output:

0 1 1 2 2 3 3 4 4 5 dtype: int64 

3. Create a Series from a Dictionary:

When you create a Series from a dictionary, the keys of the dictionary become the index of the Series:

data_dict = {'a': 1, 'b': 2, 'c': 3} series_from_dict = pd.Series(data_dict) print(series_from_dict) 

Output:

a 1 b 2 c 3 dtype: int64 

4. Create a Series from a Numpy Array:

First, ensure you have the NumPy library imported:

import numpy as np 

Now, you can create a Series from a NumPy array:

data_array = np.array([1, 2, 3, 4, 5]) series_from_array = pd.Series(data_array) print(series_from_array) 

Output:

0 1 1 2 2 3 3 4 4 5 dtype: int64 

Additional Notes:

  1. Setting Index: You can provide a custom index when creating a Series. For example:

    custom_index = ['one', 'two', 'three', 'four', 'five'] series_with_custom_index = pd.Series(data_list, index=custom_index) print(series_with_custom_index) 
  2. Data Type: A Series can also contain heterogeneous data. If the data types are mixed, the Series will try to upcast to a data type that can hold all types (e.g., if you mix integers and strings, the Series will be of object type).

  3. Name: You can assign a name to the Series object using the name parameter:

    named_series = pd.Series(data_list, name="Sample Data") print(named_series) 

With these basics, you can easily create a Series from different types of data structures and customize them as per your needs.


More Tags

mouse rubygems amazon-dynamodb-streams cs50 addeventlistener anchor subsonic bufferedimage intellij-idea ngoninit

More Programming Guides

Other Guides

More Programming Examples