Pandas Series str | center method
Start your free 7-days trial now!
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
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.
The character to pad with. By default,
fillchar=" " (whitespace).
To center pad each value to a width of
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:
NaN- this is because the method turns non-string values to
though not officially documented, for uneven cases, the fill character is added to the right side.
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