📜  Python|熊猫系列.str.center()

📅  最后修改于: 2022-05-13 01:55:35.759000             🧑  作者: Mango

Python|熊猫系列.str.center()

Series.str可用于以字符串形式访问系列的值并对其应用多种方法。 Pandas Series.str.center()函数用于在 Series/Index 中的字符串的左侧和右侧填充一个附加字符。该函数等效于 Python 的str.center()

示例 #1:使用Series.str.center()函数在给定系列对象的基础数据中用“*”符号填充字符串的左侧和右侧。

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich'])
  
# Creating the index
idx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']
  
# set the index
sr.index = idx
  
# Print the series
print(sr)

输出 :

现在我们将使用Series.str.center()函数在字符串的左侧和右侧填充“*”符号。

# fill '*' in the left and right side of string
result = sr.str.center(width = 13, fillchar = '*')
  
# print the result
print(result)

输出 :

正如我们在输出中看到的那样, Series.str.center()函数已成功在给定系列对象的基础数据中字符串的左侧和右侧填充了“*”符号。

示例 #2 :使用Series.str.center()函数在给定系列对象的基础数据中用“*”符号填充字符串的左侧和右侧。

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney'])
  
# Creating the index
idx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5']
  
# set the index
sr.index = idx
  
# Print the series
print(sr)

输出 :

现在我们将使用Series.str.center()函数在字符串的左侧和右侧填充“*”符号。

# fill '*' in the left and right side of string
# width after filling should be 5
result = sr.str.center(width = 5, fillchar = '*')
  
# print the result
print(result)

输出 :

正如我们在输出中看到的那样, Series.str.center()函数已成功在给定系列对象的基础数据中字符串的左侧和右侧填充了“*”符号。

注意:如果宽度的值小于实际字符串的长度,则打印整个字符串而不截断它。