Python Pandas – How to skip initial space from a DataFrame



To skip initial space from a Pandas DataFrame, use the skipinitialspace parameter of the read_csv() method. Set the parameter to True to remove extra space.

Let’s say the following is our csv file βˆ’

We should get the following output i.e. skipping initial whitespace and displaying the DataFrame from the CSV βˆ’

Example

Following is the complete code βˆ’

import pandas as pd

# reading csv file
dataFrame = pd.read_csv("C:\Users\amit_\Desktop\CarRecords.csv")
print("DataFrame...\n",dataFrame)

# reading csv file and removing initial space
dataFrame = pd.read_csv("C:\Users\amit_\Desktop\CarRecords.csv", skipinitialspace = True)
print("DataFrame...\n",dataFrame)

At first, read the CSV. Our CSV file is on the Desktop βˆ’

dataFrame = pd.read_csv("C:\Users\amit_\Desktop\CarRecords.csv")

While reading, you can set the skipinitialspace parameter and remove whitespace βˆ’

dataFrame = pd.read_csv("C:\Users\amit_\Desktop\CarRecords.csv", skipinitialspace = True)

Output

This will produce the following output βˆ’

DataFrame...
           Car       Place   UnitsSold
0         Audi   Bangalore          80
1      Porsche      Mumbai         110
2   RollsRoyce        Pune         100
3          BMW       Delhi         200
4     Mercedes   Hyderabad          80
5  Lamborghini  Chandigarh          80
6         Audi      Mumbai          60
7     Mercedes        Pune         120
8  Lamborghini       Delhi         100
DataFrame...
           Car       Place   UnitsSold
0         Audi   Bangalore          80
1      Porsche      Mumbai         110
2   RollsRoyce        Pune         100
3          BMW       Delhi         200
4     Mercedes   Hyderabad          80
5  Lamborghini  Chandigarh          80
6         Audi      Mumbai          60
7     Mercedes        Pune         120
8  Lamborghini       Delhi         100
Updated on: 2021-09-28T12:11:30+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements