Pandas Series: str.zfill() function
Series-str.zfill() function
The str.zfill() function is used to pad strings in the Series/Index by prepending '0' characters.
Strings in the Series/Index are padded with '0' characters on the left of the string to reach a total string length width. Strings in the Series/Index with length greater or equal to width are unchanged.
Syntax:
Series.str.zfill(self, width)
Parameters:
Name | Description | Type/Default Value | Required / Optional |
---|---|---|---|
width | Minimum length of resulting string; strings with length less than width be prepended with '0' characters. | int | Required |
Returns: Series/Index of objects
Example:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series(['-2', '2', '2000', 20, np.nan])
s
Output:
0 -2 1 2 2 2000 3 20 4 NaN dtype: object
Note that 10 and NaN are not strings, therefore they are converted to NaN. The minus sign in '-2' is treated as a regular character and the zero is added to the left of it (str.zfill() would have moved it to the left). 2000 remains unchanged as it is longer than width.
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series(['-2', '2', '2000', 20, np.nan])
s.str.zfill(3)
Output:
0 0-2 1 002 2 2000 3 NaN 4 NaN dtype: object
Previous: Series-str.wrap() function
Next: Series-str.isalnum() function
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/pandas/series/series-str-zfill.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics