Pandas index columns allow identifying each row uniquely.
You can remove the index column in pandas while reading from the CSV file using the parameter index_col=None parameter.
- By default, the
read_csv()
method doesn’t make any columns as an index. - While reading the CSV file, you have to specify if a column must be made an index column.
- Otherwise, the default arithmetic sequence number will be made as an index of the dataframe. An index is mandatory, and this cannot be removed.
You can drop the index using the following code if the file is read with an index.
Syntax
df.reset_index(drop=True, inplace=True)
df
Remove Index Using read_CSV and index_col Parameter
By default, the read_csv()
method uses the arithmetic sequence as an index.
- Pass
index_col=None
to explicitly specify no columns from the CSV file must be made an index. - The numbers starting from
0..n
will be made as an index of the pandas dataframe.
Code
import pandas as pd
df = pd.read_csv('addresses.csv', index_col=None, header=None)
df
DataFrame Will Look Like
0 | 1 | 2 | 3 | 4 | 5 | 6 | |
---|---|---|---|---|---|---|---|
0 | a-1 | John | Doe | 120 jefferson st. | Riverside | NJ | 8075 |
1 | a-2 | Vikram | Aruchamy | Chepauk, second street | Coimbatore | TamilNadu | 600100 |
Dropping Index Column
This section teaches you how to read a CSV file with an index column and drop them later.
- Use the parameter
index_col=0
to make the first column in the CSV file an index.
Code
import pandas as pd
df = pd.read_csv('addresses.csv', index_col=0, header=None)
df
DataFrame Will Look Like
1 | 2 | 3 | 4 | 5 | 6 | |
---|---|---|---|---|---|---|
0 | ||||||
a-1 | John | Doe | 120 jefferson st. | Riverside | NJ | 8075 |
a-2 | Vikram | Aruchamy | Chepauk, second street | Coimbatore | TamilNadu | 600100 |
Once you have the dataframe, you can use the reset_index()
method to reset the existing index.
- Use
drop=True
to drop the existing index - Use
inplace=True
to perform the drop operation in the same dataframe instead of creating a new dataframe
Code
df.reset_index(drop=True, inplace=True)
df
DataFrame Will Look Like
1 | 2 | 3 | 4 | 5 | 6 | |
---|---|---|---|---|---|---|
0 | John | Doe | 120 jefferson st. | Riverside | NJ | 8075 |
1 | Vikram | Aruchamy | Chepauk, second street | Coimbatore | TamilNadu | 600100 |