Pandas Series str | pad method
Series.pad(~) pads each string of the Series until the specified length is reached.
If the value is not of type string, then
NaN will be returned for that value. If all the values are not of type string, then an error will be thrown.
The desired length to pad until. If a string is larger than the specified
width, then that string is left as is.
The side of the string to pad:
Adds padding to the left.
Adds padding to the right.
Adds padding to both sides.
The character to pad with. By default,
fillchar=" " (a single whitespace).
To left-pad with
"z" until a width of
s = pd.Series(["ab", "2", 2])s.str.pad(width=5, fillchar="z") # side="left"0 zzzab1 zzzz22 NaNdtype: object
Notice how the integer
2 was turned into
NaN - this is because it is not a string.
side="both" pads both ends of each string:
s = pd.Series(["ab", "2"])s.str.pad(width=5, fillchar="z", side="both")0 zzabz1 zz2zzdtype: object
Here, notice how two
zs were added to the left of
"ab", and only one
z to the right.
Undefined padding for uneven cases
Unfortunately, there is no rule where the
fillchar always gets added to the left side first. For instance, consider the following:
s = pd.Series(["A"])s.str.pad(width=6, fillchar="z", side="both")0 zzAzzzdtype: object
In this case, we have one additional
z on the right as opposed to the left.
Case when overflow
When a string is larger than the specified
width, then it is left as is:
s = pd.Series(["abbbbb", "20000"])s.str.pad(width=2, fillchar="z", side="both")0 abbbbb1 20000dtype: object