Showing posts with label series. Show all posts
Showing posts with label series. Show all posts

Thursday, 14 September 2023

Pandas: A Guide to Traversing Series

In this post, I am going to explain different ways to traverse the Pandas Series.

Approach 1: Using for loop and series index attribute.

for index_label in series.index:
    value = series[index_label]
    print(f"Index: {index_label}, Value: {value}")

Approach 2: Using enumerate method.

for index_position, index_label in enumerate(series.index):
    print(f"Index: {index_position}, Label: {index_label}, Value: {series[index_label]}")

Approach 3: Using series items method.

for index_label, value in series.items():
    print(f"Index: {index_label}, Value: {value}")

traverse_series.py

import pandas as pd

primes_list = [2, 3, 5, 7]
index_labels = ['A', 'B', 'C', 'D']
series = pd.Series(primes_list, index=index_labels)

# Using for loop and series index attribute.
print('Using for loop and series index attribute.')
for index_label in series.index:
    value = series[index_label]
    print(f"Index: {index_label}, Value: {value}")

# Using enumerate method
print('\nUsing for loop and series index attribute.')
for index_position, index_label in enumerate(series.index):
    print(f"Index: {index_position}, Label: {index_label}, Value: {series[index_label]}")

# Using series items method
print('\nUsing series items method')
for index_label, value in series.items():
    print(f"Index: {index_label}, Value: {value}")

Output

Using for loop and series index attribute.
Index: A, Value: 2
Index: B, Value: 3
Index: C, Value: 5
Index: D, Value: 7

Using for loop and series index attribute.
Index: 0, Label: A, Value: 2
Index: 1, Label: B, Value: 3
Index: 2, Label: C, Value: 5
Index: 3, Label: D, Value: 7

Using for loop and series index attribute.
Index: A, Value: 2
Index: B, Value: 3
Index: C, Value: 5
Index: D, Value: 7


Previous                                                 Next                                                 Home

Sunday, 10 September 2023

Joining Elements of a Pandas Series with a Delimiter

Using String join() method, we can join the elements of a series using given delimeter.

 

Example

series = pd.Series(['India', 'China', 'Bangladesh', 'Sri Lanka'], index = ['A', 'B', 'C', 'D'])
join_by_comma = ', '.join(series)

 

In the above example, I defined a Pandas Series called ‘series’ with values ['India', 'China', 'Bangladesh', 'Sri Lanka']. Using the statement

', '.join(series) method on the series object, we join the elements of the Series into a single string using the specified delimiter ', '.

 

join_series_elements.py
import pandas as pd

series = pd.Series(['India', 'China', 'Bangladesh', 'Sri Lanka'], index = ['A', 'B', 'C', 'D'])
join_by_comma = ', '.join(series)
join_by_colon = ': '.join(series)

print('join_by_comma : ', join_by_comma)
print('\njoin_by_colon : ', join_by_colon)

 

Output

join_by_comma :  India, China, Bangladesh, Sri Lanka

join_by_colon :  India: China: Bangladesh: Sri Lanka

 

 

Previous                                                 Next                                                 Home

Thursday, 7 September 2023

Convert Pandas Series to Dictionary

‘dict’ method takes a series object and return the dictionary. The resulting dictionary have series index values as key and corresponding values as dictionary values.

 

Example 1: With default numeric index

primes = [2, 3, 5, 7]
series = pd.Series(primes)
primes_dict = dict(series)

 

‘primes_dict’ contain below values.

{0: 2, 1: 3, 2: 5, 3: 7}

 

Example 2: With index labels.
index_labels = ['first_prime', 'second_prime', 'third_prime', 'fourth_prime']
series = pd.Series(primes, index_labels)
primes_dict = dict(series)

 

‘primes_dict’ contain the below data.

{'first_prime': 2, 'second_prime': 3, 'third_prime': 5, 'fourth_prime': 7}

 

convert_list_to_dictionary.py

import pandas as pd

primes = [2, 3, 5, 7]
series = pd.Series(primes)

print('Original Data : ')
print(series)

primes_dict = dict(series)
print('primes_dict : ', primes_dict)

index_labels = ['first_prime', 'second_prime', 'third_prime', 'fourth_prime']
series = pd.Series(primes, index_labels)

print('\nOriginal Data : ')
print(series)

primes_dict = dict(series)
print('primes_dict : ', primes_dict)

 

Output

Original Data : 
0    2
1    3
2    5
3    7
dtype: int64
primes_dict :  {0: 2, 1: 3, 2: 5, 3: 7}

Original Data : 
first_prime     2
second_prime    3
third_prime     5
fourth_prime    7
dtype: int64
primes_dict :  {'first_prime': 2, 'second_prime': 3, 'third_prime': 5, 'fourth_prime': 7}

 

 

Previous                                                 Next                                                 Home

Tuesday, 5 September 2023

Python built-in functions to work with series data

Following table summarizes the Python built-in functions that can be used with series data.

 

Functions

Description

dict

Get the dictionary from series data

dir

Get all the available attributes and methods available in series object

len

Get number of elements in a series

list

Get the list from series data

max

Get the maximum value in the series

min

Get the minimum value in the series

sorted

Sort the values of series

type

Tells whether given variable is a series object or not.

 

Previous                                                 Next                                                 Home

Pandas: Get the last n elements of the series

Using tail method, we can get the rows from the series end

 

Example

series.tail() : Return last 5 rows in the series.
series.tail(n) : Return last n rows in the series.

 

Find the below working application.

 

tail.py
import pandas as pd

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
series = pd.Series(primes)

print('Original Data : ')
print(series)

last_five_primes = series.tail()
last_three_primes = series.tail(3)

print('\nlast_five_primes')
print(last_five_primes)

print('\nlast_three_primes')
print(last_three_primes)

 

Output

Original Data : 
0      2
1      3
2      5
3      7
4     11
5     13
6     17
7     19
8     23
9     29
10    31
dtype: int64

last_five_primes
6     17
7     19
8     23
9     29
10    31
dtype: int64

last_three_primes
8     23
9     29
10    31
dtype: int64

‘tail()’ method is a preview on original dataset, if you update something on the result returned by tail() method, it updates the original data. You can confirm the same from below application.

 

tail.py

import pandas as pd

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
series = pd.Series(primes)

print('Original Data : ')
print(series)

last_five_primes = series.tail()
last_three_primes = series.tail(3)

print('\nlast_five_primes')
print(last_five_primes)

print('\nlast_three_primes')
print(last_three_primes)

Output

Original Data : 
0      2
1      3
2      5
3      7
4     11
5     13
6     17
7     19
8     23
9     29
10    31
dtype: int64

last_five_primes
6     17
7     19
8     23
9     29
10    31
dtype: int64

last_three_primes
8     23
9     29
10    31
dtype: int64

 

Previous                                                 Next                                                 Home

Pandas: Get the First n Elements of a Series

Using 'head()' method we can get 'n' number of rows from the dataset.

 

Example

head() : Get 5 rows from the beginning
head(n) : Get n rows from the beginning

 

head.py

import pandas as pd

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
series = pd.Series(primes)

print('Original Data : ')
print(series)

first_five_primes = series.head()
first_three_primes = series.head(3)

print('\nfirst_five_primes')
print(first_five_primes)

print('\nfirst_three_primes')
print(first_three_primes)

 

Output

Original Data : 
0      2
1      3
2      5
3      7
4     11
5     13
6     17
7     19
8     23
9     29
10    31
dtype: int64

first_five_primes
0     2
1     3
2     5
3     7
4    11
dtype: int64

first_three_primes
0    2
1    3
2    5
dtype: int64

‘head()’ method is a preview on original dataset, if you update something on the result returned by head() method, it updates the original data.



 

head_preview_update.py

import pandas as pd

primes = [2, 3, 5, 7]
series = pd.Series(primes)

print('Original Data : ')
print(series)

print('\nUpdating 1st prime to 11')
first_two_primes = series.head(2)
first_two_primes[0] = 11

print('\nAfter updating\n')
print(series)

Output

Original Data : 
0    2
1    3
2    5
3    7
dtype: int64

Updating 1st prime to 11

After updating

0    11
1     3
2     5
3     7
dtype: int64

 

Previous                                                 Next                                                 Home

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