Pandas Series.str.ljust() 方法



Python Pandas 库中的Series.str.ljust() 方法用于将 Series 或 Index 中字符串的右侧填充到指定的最小宽度。

这相当于 Python 中的字符串方法str.ljust()。该方法确保 Series 或 Index 中的每个字符串至少具有指定的宽度,如有必要,则使用指定的填充字符进行填充。

语法

以下是 Pandas Series.str.ljust() 方法的语法:

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

参数

Series.str.ljust() 方法接受以下参数:

  • width - 指定结果字符串最小宽度的整数。其他字符将用fillchar填充。

  • fillchar - 指定用于填充的其他字符的字符串。默认为空格字符。

返回值

Series.str.ljust() 方法返回一个包含右侧填充字符串的 Series 或 Index 对象。

示例 1

在这个例子中,我们演示了Series.str.ljust() 方法的基本用法,使用填充字符“.”将 Series 中的字符串右侧填充到宽度为 8。

import pandas as pd

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

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

# Right-pad the strings 
print("Series after calling ljust with width=8 and fillchar='.'")
print(s.str.ljust(8, fillchar='.'))

运行上述代码后,将产生以下输出:

Input Series
0      dog
1     lion
2    panda
dtype: object

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

示例 2

此示例演示如何使用Series.str.ljust() 方法使用填充字符“-”将 DataFrame 列中的字符串右侧填充到宽度为 10。

import pandas as pd

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

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

# Right-pad the strings in the 'Animal' column 
df['Animal'] = df['Animal'].str.ljust(10, fillchar='-')

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

以下是上述代码的输出:

Input DataFrame:
     Animal  Legs
0    Python     4
1  Tutorial     4
2     panda     2

DataFrame after applying ljust with width=10 and fillchar='-':
      Animal  Legs
0    Python--     4
1  Tutorial-     4
2    panda---     2

示例 3

在这个例子中,我们应用Series.str.ljust() 方法使用填充字符“*”将 DataFrame 的索引标签右侧填充到宽度为 10。

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)

# Right-pad the index labels of a DataFrame
df.index = df.index.str.ljust(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.