> ## Content Index
> Fetch the complete content index at: https://datascientyst.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Trim Leading & Trailing White Space in Pandas DataFrame
- URL: https://datascientyst.com/trim-leading-trailing-white-space-pandas-dataframe/
- Published: 2023-11-24T14:08:36.000Z
- Updated: 2023-11-24T14:09:13.000Z
- Author: John D K
- Tags: replace()

**To trim leading and trailing whitespaces from strings in Pandas DataFrame**, you can use the `str.strip()` function to trim leading and trailing whitespaces from strings. Here's an example:

```python
import pandas as pd

data = {'col_1': ['  Apple  ', ' Banana', 'Orange  ', '   Grape   '],
        'col_2': ['   Red ', 'Yellow   ', '  Orange', 'Purple   ']}

df = pd.DataFrame(data)

```

sample data is:

|   | col\_1 | col\_2 |
| - | ------ | ------ |
| 0 | Apple  | Red    |
| 1 | Banana | Yellow |
| 2 | Orange | Orange |
| 3 | Grape  | Purple |

Browsers usually hide extract spaces at start and end - so you can find row DataFrame data below:

```
         col_1      col_2
0      Apple         Red 
1       Banana  Yellow   
2     Orange       Orange
3     Grape     Purple   

```

## 1\. remove spaces - whole DataFrame

**To remove leading and trailing whitespaces** in all columns we can:

```python
df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)

```

result:

```
    col_1   col_2
0   Apple     Red
1  Banana  Yellow
2  Orange  Orange
3   Grape  Purple

```

In this example, the `applymap()` function is used to apply the `strip()` method to each element in the DataFrame. The lambda function checks if the element is a string (isinstance(x, str)) before applying the strip method to avoid errors for non-string elements.

After running this code, you'll get a DataFrame where leading and trailing whitespaces in all string columns have been removed.

## 2\. strip spaces in single column

To remove trailing and leading spaces from a single column in Pandas DataFrame we can use:

- Series method `strip()`
- `map` \+ `strip()`:

```python
df['col_1'].str.strip()

```

```python
df['col_1'].map(lambda x: x.strip() if isinstance(x, str) else x)

```

or

output:

```
0     Apple
1    Banana
2    Orange
3     Grape
Name: col_1, dtype: object

```

## 3\. trim trailing spaces with regex

As alternative solution we an use method `replace()` to remove leading and trailing whitespaces.

```python
df.replace(r"^ +| +$", r"", regex=True)

```

result:

```
    col_1   col_2
0   Apple     Red
1  Banana  Yellow
2  Orange  Orange
3   Grape  Purple

```

## lstrip + rstrip

Pandas offers to handy methods for removing extra spaces: `rstrip` and `lstrip`:

```python
s.str.rtrip()
s.str.ltrip()

```

![](https://datascientyst.com/content/images/2023/11/trim-leading-trailing-white-space-pandas-dataframe.png)

## Resources

- [pandas.Series.str.strip](https://pandas.pydata.org/docs/reference/api/pandas.Series.str.strip.html?ref=datascientyst.com)
- [pandas.Series.str.rstrip](https://pandas.pydata.org/docs/reference/api/pandas.Series.str.rstrip.html?ref=datascientyst.com)
- [pandas.Series.str.lstrip](https://pandas.pydata.org/docs/reference/api/pandas.Series.str.lstrip.html?ref=datascientyst.com)
- [pandas.Series.replace](https://pandas.pydata.org/docs/reference/api/pandas.Series.replace.html?ref=datascientyst.com)
- [pandas.DataFrame.replace](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html?ref=datascientyst.com)
- [Pandas trim leading & trailing white space in a dataframe](https://stackoverflow.com/questions/49551336/pandas-trim-leading-trailing-white-space-in-a-dataframe?ref=datascientyst.com)