Pandas Series str | center method
Start your free 7-days trial now!
Pandas Series.str.center(~)
pads the left and right side of each string in the Series until the specified width is reached. If the length of the string is larger than the specified width, then the string is left as is.
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.
Parameters
1. width
| int
The desired length to pad until.
2. fillchar
| string
The character to pad with. By default, fillchar=" "
(whitespace).
Return Value
A Series
.
Examples
Basic usage
To center pad each value to a width of 4
:
s = pd.Series(["ab", "2", 2, pd.np.nan])s.str.center(width=4, fillchar="A")
0 AabA1 A2AA2 NaN3 NaNdtype: object
Here, note the following:
the value
2
turned intoNaN
- this is because the method turns non-string values toNaN
.though not officially documented, for uneven cases, the fill character is added to the right side.
Overflow case
When the length of a string is larger than the specified width
, it is left as is:
s = pd.Series(["aaaaa", "aa"])s.str.center(width=4, fillchar="A")
0 aaaaa1 AaaAdtype: object