Pandas Series str | pad method
Start your free 7-days trial now!
Pandas 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.
Parameters
1. width | int
The desired length to pad until. If a string is larger than the specified width, then that string is left as is.
2. side | string | optional
The side of the string to pad:
Value  | Description  | 
|---|---|
  | Adds padding to the left.  | 
  | Adds padding to the right.  | 
  | Adds padding to both sides.  | 
By default, side="left".
3. fillchar | string | optional
The character to pad with. By default, fillchar=" " (a single whitespace).
Return Value
A Series object.
Examples
Basic usage
To left-pad with "z" until a width of 5:
        
        
            
                
                
                    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.
Specifying side=both
Passing 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