Pandas Series.str.center() Method



The Series.str.center() method in Pandas is used to pad both the left and right sides of strings in a Series or Index to a specified width.

This method ensures that the string is centered within the new width, with additional characters filled by a specified fill character. This operation is similar to the string method str.center() in Python.

Syntax

Following is the syntax of the Pandas Series.str.center() method −

Series.str.center(width, fillchar=' ')

Parameters

The Series.str.center() method accepts the following parameters −

  • width: An integer specifying the minimum width of the resulting string. Additional characters will be filled with fillchar.
  • fillchar: A string specifying the character for filling, default is whitespace.

Return Value

The Series.str.center() method returns a new Series with the strings centered and padded to the specified width using the specified fill character.

Example 1

In this example, we demonstrate the basic usage of the Series.str.center() method by applying it to a Series of strings.

import pandas as pd

# Create a Series of strings
s = pd.Series(['dog', 'lion', 'panda'])

# Display the input Series
print("Input Series")
print(s)

# Center the strings with a width of 8 and fill character '.'
print("Series after calling center with width=8 and fillchar='.':")
print(s.str.center(8, fillchar='.'))

When we run the above code, it produces the following output

Input Series
0      dog
1     lion
2    panda
dtype: object

Series after calling center with width=8 and fillchar='.':
0    ..dog...
1    ..lion..
2    .panda..
dtype: object

Example 2

This example demonstrates how to use the Series.str.center() method to format the 'Animal' column in a DataFrame, by centering each animal name to a specified width with a custom fill character.

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'Animal': ['dog', 'lion', 'panda'], 'Legs': [4, 4, 2]})

print("Input DataFrame:")
print(df)

# Center the strings in the 'Animal' column with a width of 8 and fill character '-'
df['Animal'] = df['Animal'].str.center(8, fillchar='-')

print("DataFrame after applying center with width=8 and fillchar='-':")
print(df)

Following is the output of the above code −

Input DataFrame:
  Animal  Legs
0    dog     4
1   lion     4
2  panda     2

DataFrame after applying center with width=8 and fillchar='-':
    Animal  Legs
0  --dog---     4
1  --lion--     4
2  -panda--     2

Example 3

In this example, we apply the Series.str.center() method to an Index object. This showcases how you can use it to format the index labels in a DataFrame by centering them with a specified width and fill character.

import pandas as pd

# Create a DataFrame with an Index
df = pd.DataFrame({'Value': [1, 2, 3]}, index=['first', 'second', 'third'])

# Display the Input DataFrame
print("Input DataFrame:")
print(df)

# Center the index labels with a width of 10 and fill character '*'
df.index = df.index.str.center(10, fillchar='*')

# Display the Modified DataFrame
print("Modified DataFrame:")
print(df)

Output of the above code is as follows −

Input DataFrame:
        Value
first       1
second      2
third       3

Modified DataFrame:
            Value
**first***      1
**second**      2
**third***      3
python_pandas_working_with_text_data.htm
Advertisements
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy