Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python - Read csv file with Pandas without header?
To read a CSV file without headers in Pandas, use the header=None parameter in the read_csv() method. This treats the first row as data rather than column names.
Default CSV Reading (With Header)
By default, Pandas treats the first row as column headers ?
import pandas as pd
# Sample CSV data (normally you'd read from a file)
csv_data = """Car,Reg_Price,Units
BMW,2500,100
Lexus,3500,80
Audi,2500,120
Jaguar,2000,70
Mustang,2500,110"""
# Save to a temporary file for demonstration
with open('sample.csv', 'w') as f:
f.write(csv_data)
# Read CSV with default header behavior
df_with_header = pd.read_csv('sample.csv')
print("Reading CSV with header:")
print(df_with_header)
Reading CSV with header:
Car Reg_Price Units
0 BMW 2500 100
1 Lexus 3500 80
2 Audi 2500 120
3 Jaguar 2000 70
4 Mustang 2500 110
Reading CSV Without Header
Use header=None to treat all rows as data ?
import pandas as pd
# Read the same CSV without treating first row as header
df_no_header = pd.read_csv('sample.csv', header=None)
print("Reading CSV without header:")
print(df_no_header)
Reading CSV without header:
0 1 2
0 Car Reg_Price Units
1 BMW 2500 100
2 Lexus 3500 80
3 Audi 2500 120
4 Jaguar 2000 70
5 Mustang 2500 110
Adding Custom Column Names
You can assign custom column names using the names parameter ?
import pandas as pd
# Read CSV without header and assign custom column names
df_custom_names = pd.read_csv('sample.csv', header=None, names=['Vehicle', 'Price', 'Stock'])
print("Reading CSV with custom column names:")
print(df_custom_names)
Reading CSV with custom column names:
Vehicle Price Stock
0 Car Reg_Price Units
1 BMW 2500 100
2 Lexus 3500 80
3 Audi 2500 120
4 Jaguar 2000 70
5 Mustang 2500 110
Key Parameters
| Parameter | Value | Effect |
|---|---|---|
header=0 |
Default | First row as column names |
header=None |
No header | Auto-generated column names (0, 1, 2...) |
names=['col1', 'col2'] |
Custom names | Use specified column names |
Conclusion
Use header=None to read CSV files without treating the first row as column headers. Combine with names parameter to assign custom column names when needed.
Advertisements
