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. p>
Syntax: Series.str.repeat (repeats)
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 p>
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.
As shown in the output image, each line in the series was repeated twice.
Example # 2: different values for each line p>
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.
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)