Repeat The Elements In A Pandas Series

Overview:

  • The repeat() method of pandas series returns a new series, with its elements repeating as per the specified frequency.
  • The repeat frequency can be specified for all the elements or at per element basis.
  • While a frequency of 0 will result in absence of a series or absence of an element, a frequency of 1 will not repeat the element, a frequency of 2 will repeat the element once, a frequency of 3 will repeat the element twice and so on.

Example:

# Example Python program to obtain a pandas Series

# of repeating entries from an existing pandas Series

import pandas as pds

 

evenNumbers = (2, 4, 6, 8);

series      = pds.Series(evenNumbers);

print("Original series:");

print(series);

 

# Create a new series where each element is repeated twice

newSeries1  = series.repeat(2);

print("New Series1:");

print(newSeries1);

 

# Create a new series with the repeating frequency for each element

# is specified

newSeries2  = series.repeat((0, 1, 2, 3));

print("New Series2:");

print(newSeries2);

 

Output:

Original series:

0    2

1    4

2    6

3    8

dtype: int64

New Series1:

0    2

0    2

1    4

1    4

2    6

2    6

3    8

3    8

dtype: int64

New Series2:

1    4

2    6

2    6

3    8

3    8

3    8

dtype: int64

 


Copyright 2022 © pythontic.com