Pandas Series.str.center() 方法



Pandas 中的Series.str.center() 方法用于将 Series 或 Index 中的字符串的左右两侧填充到指定的宽度。

此方法确保字符串在新宽度内居中,并使用指定的填充字符填充其他字符。此操作类似于 Python 中的字符串方法str.center()

语法

以下是 Pandas Series.str.center() 方法的语法 -

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

参数

Series.str.center() 方法接受以下参数 -

  • width:指定结果字符串的最小宽度的整数。其他字符将使用fillchar填充。
  • fillchar:指定填充字符的字符串,默认为空格。

返回值

Series.str.center() 方法返回一个新的 Series,其中字符串已居中并使用指定的填充字符填充到指定的宽度。

示例 1

在此示例中,我们演示了Series.str.center() 方法的基本用法,将其应用于字符串的 Series。

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='.'))

当我们运行以上代码时,它会产生以下输出 -

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

示例 2

此示例演示了如何使用Series.str.center() 方法格式化 DataFrame 中的“Animal”列,通过使用自定义填充字符将每个动物名称居中到指定的宽度。

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)

以下是以上代码的输出 -

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

示例 3

在此示例中,我们将Series.str.center() 方法应用于 Index 对象。这展示了如何使用它通过使用指定的宽度和填充字符居中来格式化 DataFrame 中的索引标签。

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)

以上代码的输出如下 -

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
广告

© . All rights reserved.