22 Dec Remove Whitespace in Pandas
To remove whitespace on text data in a Series or DataFrame, use the following methods in Python Pandas:
- strip(): Strip whitespace from the left and right
- lstrip(): Strip whitespace from only the left side
- rstrip(): Strip whitespace from only the right side
strip() method
To strip whitespace from both the left and right side of values in a Series or DataFrame, use the strip() method in Pandas. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import pandas as pd # Data to be stored in the Pandas Series data = ['Jacob ', ' Amit', 'Trent ', 'Nathan Lyon', ' Martin'] # Create a Series using the Series() method s = pd.Series(data) # Display the Series print("Series: \n", s) # Strip the values print("\nStrip whitespace from both the sides: \n",s.str.strip()) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Series: 0 Jacob 1 Amit 2 Trent 3 Nathan Lyon 4 Martin Strip whitespace from both the sides: 0 Jacob 1 Amit 2 Trent 3 Nathan Lyon 4 Martin |
lstrip() method
To strip whitespace from the left side of values in a Series or DataFrame, use the lstrip() method in Pandas. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import pandas as pd # Data to be stored in the Pandas Series data = ['Jacob ', ' Amit', 'Trent ', 'Nathan Lyon', ' Martin'] # Create a Series using the Series() method s = pd.Series(data) # Display the Series print("Series: \n", s) # Strip the values from the left side print("\nStrip whitespace from the left sides: \n",s.str.lstrip()) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Series: 0 Jacob 1 Amit 2 Trent 3 Nathan Lyon 4 Martin Strip whitespace from the left sides: 0 Jacob 1 Amit 2 Trent 3 Nathan Lyon 4 Martin |
rstrip() method
To strip whitespace from the right side of values in a Series or DataFrame, use the rstrip() method in Pandas. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import pandas as pd # Data to be stored in the Pandas Series data = ['Jacob ', ' Amit', 'Trent ', 'Nathan Lyon', ' Martin'] # Create a Series using the Series() method s = pd.Series(data) # Display the Series print("Series: \n", s) # Strip the values from the right side print("\nStrip whitespace from the right sides: \n",s.str.rstrip()) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Series: 0 Jacob 1 Amit 2 Trent 3 Nathan Lyon 4 Martin dtype: object Strip whitespace from the right sides: 0 Jacob 1 Amit 2 Trent 3 Nathan Lyon 4 Martin |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments