Tuesday 6 February 2024

Pandas: Trim whitespaces using strip, lstrip and rstrip methods

Using strip(), lstrip(), rstrip() methods we can remove the whitespaces in given column values.

 

a.   strip(): Remove leading and trailing whitespace from the given column.

b.   lstrip(): Remove leading whitespace from the given column.

c.    rstrip(): Remove trailing whitespace from the given column.

 

trim_spaces.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna   ', 'Sailu', 'Joel  ', '   kranthi', '   Jitendra', "Kumar"],
        'Hobbies': ['Football,Cricket  ', '    Tennis, cricket   ', '   Trekking, reading books', 'Chess', 'Read Books', 'Cricket']}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

new_data = {}
new_df = pd.DataFrame(data)
new_df['Name'] = df['Name'].str.strip()
new_df['Hobbies'] = df['Hobbies'].str.strip()
print('\nDataFrame after trimming whitespaces\n',new_df)

new_df = pd.DataFrame(data)
new_df['Name'] = df['Name'].str.lstrip()
new_df['Hobbies'] = df['Hobbies'].str.lstrip()
print('\nDataFrame after trimming leading whitespaces\n',new_df)

new_df = pd.DataFrame(data)
new_df['Name'] = df['Name'].str.rstrip()
new_df['Hobbies'] = df['Hobbies'].str.rstrip()
print('\nDataFrame after trimming trailing whitespaces\n',new_df)

 

Output

Original DataFrame
          Name                     Hobbies
0   Krishna             Football,Cricket  
1        Sailu          Tennis, cricket   
2       Joel       Trekking, reading books
3      kranthi                       Chess
4     Jitendra                  Read Books
5        Kumar                     Cricket

DataFrame after trimming whitespaces
        Name                  Hobbies
0   Krishna         Football,Cricket
1     Sailu          Tennis, cricket
2      Joel  Trekking, reading books
3   kranthi                    Chess
4  Jitendra               Read Books
5     Kumar                  Cricket

DataFrame after trimming leading whitespaces
          Name                  Hobbies
0  Krishna          Football,Cricket  
1       Sailu       Tennis, cricket   
2      Joel    Trekking, reading books
3     kranthi                    Chess
4    Jitendra               Read Books
5       Kumar                  Cricket

DataFrame after trimming trailing whitespaces
           Name                     Hobbies
0      Krishna            Football,Cricket
1        Sailu             Tennis, cricket
2         Joel     Trekking, reading books
3      kranthi                       Chess
4     Jitendra                  Read Books
5        Kumar                     Cricket

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment