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: 28-Sep-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements