ADVERTISEMENT
ADVERTISEMENT

Different Operations on Series in Pandas with Examples

Pandas Series is a one-dimensional labeled array that is capable of holding any type of data (integer, string, float, python objects, etc.). It is somewhat similar to a dictionary, only it allows for more powerful, flexible usage. A Pandas Series can be created from lists, dictionaries, and from a scalar value, etc.

From creation and indexing to handling missing data, this tutorial covers the essential operations you need to analyze and process data effectively.

Here are some basic operations you can perform on a Pandas Series:

1. Creation: Creating a new Series.

import pandas as pd

# Creating series from a list
s = pd.Series([1, 3, 5, 6, 8])
print(s)

 2. Indexing/Selection: Accessing data from series with position.

import pandas as pd

# Creating series s = pd.Series([1, 3, 5, 6, 8])

# Accessing the first element
print(s[0])

# Accessing elements starting from index 1 till 3 (excluding 3)
print(s[1:3])

# Accessing elements with specific indexes
print(s[[0, 2, 4]])

3. Assignment: You can modify the Series in place by assigning to the indexer.

# Assigning a new value at index 0
s[0] = 999
print(s)

4. Deletion: Deleting an item from a series.

# Deleting an item at index 0
s = s.drop([0])
print(s)

5. Mathematical Operations: Performing mathematical operations on series.

# Adding a constant to a series
s = s + 2
print(s)

# Multiplying a series with a constant
s = s * 3
print(s)

6. Statistical Operations: You can perform various statistical operations on Series like count, sum, mean, median, mode, min, max, standard deviation, variance, etc.

# Sum of all values in series
print(s.sum())

# Mean of all values in series
print(s.mean())

7. Conversion: Converting Series into other data structures.

# Converting series to a list
list_s = s.tolist()
print(list_s)

# Converting series to a dictionary
dict_s = s.to_dict()
print(dict_s)

8. Sorting: You can sort a series by its index or its values.

# Sorting by index
s = s.sort_index()
print(s)

# Sorting by values
s = s.sort_values()
print(s)

9. Handling Missing Data: You can detect and/or eliminate missing data.

# Detect missing data
print(s.isnull())

# Drop missing data
s = s.dropna()
print(s)

10. Applying functions: You can apply functions to a series.

# Applying a lambda function that squares all the values
s = s.apply(lambda x: x**2)
print(s)

 


ADVERTISEMENT

ADVERTISEMENT