📅  最后修改于: 2023-12-03 15:34:16.392000             🧑  作者: Mango
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.
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.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
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
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
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.