📌  相关文章
📜  Python| Pandas Series.str.strip()、lstrip() 和 rstrip()(1)

📅  最后修改于: 2023-12-03 15:34:16.392000             🧑  作者: Mango

Python | Pandas Series.str.strip(), lstrip() and rstrip()

1. Introduction

In Pandas, the Series.str.strip(), Series.str.lstrip() and Series.str.rstrip() methods are used to remove whitespace (or other characters) from the start and end of a string. These methods work only on string-type series.

2. Syntax

The syntax for these methods is:

  • Series.str.strip([chars]): removes the leading and trailing characters specified in chars.
  • Series.str.lstrip([chars]): removes the leading characters specified in chars.
  • Series.str.rstrip([chars]): removes the trailing characters specified in chars.

Parameters

  • chars: str, default None - Characters to be removed from the start or end of each string in the Series/Index.
3. Examples
Example 1: Using Series.str.strip()
import pandas as pd

# Create a Series with strings containing leading/trailing spaces
s = pd.Series(['  abc', 'def  ', '  ghi ', 'jkl'])

# Remove leading/trailing spaces
s = s.str.strip()

# Display the updated Series
print(s)

Output:

0    abc
1    def
2    ghi
3    jkl
dtype: object
Example 2: Using Series.str.lstrip()
import pandas as pd

# Create a Series with strings containing leading spaces
s = pd.Series(['  abc', '  def', '  ghi ', 'jkl'])

# Remove leading spaces
s = s.str.lstrip()

# Display the updated Series
print(s)

Output:

0     abc
1     def
2    ghi 
3     jkl
dtype: object
Example 3: Using Series.str.rstrip()
import pandas as pd

# Create a Series with strings containing trailing spaces
s = pd.Series(['abc  ', 'def ', '  ghi', 'jkl'])

# Remove trailing spaces
s = s.str.rstrip()

# Display the updated Series
print(s)

Output:

0    abc
1    def
2    ghi
3    jkl
dtype: object
4. Conclusion

In conclusion, we have covered the Series.str.strip(), Series.str.lstrip(), and Series.str.rstrip() methods in Pandas. These methods are useful when working with string-type Series data and allow us to remove leading and trailing characters (including whitespace) from each element in the Series.