This tutorial includes two methods to read CSV without the first column in Python.
Method 1:
pd.read_csv(“CSV_file_name”,index_col=0)
Method 2:
df=pd.read_csv(“CSV_file_name”)
del df[df.columns[0]]
Example for Method 1
The following is an example showing without and with index_col=0
in read.csv()
.
import pandas as pd
# read the csv file from Github, without index_col=0
df_raw=pd.read_csv("https://raw.githubusercontent.com/TidyPython/CSV_Sample/main/car_data.csv")
# print out the original dataframe
print('Raw Dataframe: \n',df_raw)
# read the csv file from Github, with index_col=0
df_removed=pd.read_csv("https://raw.githubusercontent.com/TidyPython/CSV_Sample/main/car_data.csv", index_col=0)
# print out the dataframe removed the first column
print('Removed Dataframe: \n', df_removed)
The following is the output, which includes both versions of dataframe. In the removed dataframe, we remove the first column of data. To remove the first column, we can add index_col=0
in read_csv()
.
Raw Dataframe: Unnamed: 0 Brand Location Year 0 0 Tesla CA 2019 1 1 Ford CA 2018 2 2 Tesla NY 2020 3 3 Ford MA 2019 Removed Dataframe: Brand Location Year 0 Tesla CA 2019 1 Ford CA 2018 2 Tesla NY 2020 3 Ford MA 2019
Example for Method 2
We can first read the CSV file using Pandas, and then we can del
to remove the first column of data.
import pandas as pd
# read the csv file from Github, without index_col=0
df=pd.read_csv("https://raw.githubusercontent.com/TidyPython/CSV_Sample/main/car_data.csv")
# print out the original dataframe
print('Raw Dataframe: \n',df)
# remove the first column of data frame
del df[df.columns[0]]
# print out the dataframe removed the first column
print('Removed Dataframe: \n', df)
The following is the output. As we can see, raw dataframe has one additional index column.
Raw Dataframe: Unnamed: 0 Brand Location Year 0 0 Tesla CA 2019 1 1 Ford CA 2018 2 2 Tesla NY 2020 3 3 Ford MA 2019 Removed Dataframe: Brand Location Year 0 Tesla CA 2019 1 Ford CA 2018 2 Tesla NY 2020 3 Ford MA 2019
Further Reading
The following shows a few other tutorials about reading CSV and Excel files in Python.