+

Python | Pandas Series.str.repeat ()

str.repeat() Pandas str.repeat() is used to repeat string values ​​in the same positions of the most skipped row. An array can also be passed in case you need to determine how many times each element should be repeated in sequence. In this case, the length of the array must be the same as the length of the series. 
.str must be prefixed every time before calling this function, as it is a string method, and also distinguish it from the default repeat method in python.

Syntax: Series.str.repeat (repeats)

Parameters:
repeats: int or List of int to define number of times string has to be repeated. (Size of list must be equal to series)

Return type: Series with repeated values ​​

To load the CSV used in the code, click here.

In the following examples, the data frame used contains data for some NBA players. An image of the data frame before any operations is attached below. 

Example # 1: repeating the same number of times

In this example, one integer is passed as the repeat parameter, and therefore each string value in the series will be repeated the same number of times. Zero values ​​must be removed before any operation can be applied to avoid errors. Hence the dropna () method is used to remove null values.

# pandas module import

import pandas as pd

  
# create data frame

data = pd.read_csv ( " https://media.python.engineering/wp-content/uploads/nba.csv " )

 
# remove null values ​​to avoid errors

data.dropna (how = `a ll` , inplace = True )

 
# overwrite with repeated value

data [ "Team" ] = data [ "Team" ] . str . repeat ( 2 )

 
# display
data

Output:
As shown in the output image, each line in the series was repeated twice. 

Example # 2: different values ​​for each line

This example creates a 10-row sample data frame using the .head () method. After that, a list of 10 integers is created and passed to the repeat () function to repeat each line a different number of times.

# pandas module import

import pandas as pd

  
# create data frame

data = pd.read_csv ( " https://media.python.engineering/wp-content/uploads/nba.csv " )

 
# remove null values ​​to avoid errors

data.dropna ( how = `all` , inplace = True )

 
# create data from 10 lines

sample_data = data.head ( 10 ). copy ()

 
# create a list of 10 int

repeat_list = [ 2 , 1 , 3 , 4 , 1 , 5 , 0 , 6 , 1 , 2 ]

 
# call the repeat function

sample_data [ "Name" ] = sample_data [ " Name " ]. str . Repeat (repeat_list)

 
# data display
sample_data

Output:
As shown in the output image, the line is repeated according to with an integer present at the same index in repeat_list.

Note: one of the values ​​in the list is set to 0, and therefore the string was repeated 0 times in the final series (the most significant the string value was also removed and remained empty)

Get Solution for free from DataCamp guru