How to read a Pandas CSV file with no header?

PythonServer Side ProgrammingProgramming

To read a CSV file with no header, we can use headers in read_csv() method.

Steps

  • Initialize a variable file_path, i,e., CSV file path.
  • Use read_csv method to get the DataFrame with tab separator and with headers.
  • Print the DataFrame with headers.
  • Use read_csv method to get the DataFrame with tab separator and without headers. To read without headers, use header=0.
  • Print the DataFrame without headers.

Example

import pandas as pd

file_path = 'test.csv'

// With Headers
df = pd.read_csv(file_path, sep='\t', names=['x', 'y', 'z'])
print "With headers, the DataFrame is: \n", df

// Without Headers
df = pd.read_csv(file_path, sep='\t', header=0, names=['x', 'y', 'z'])
print "Without headers, the DataFrame is: \n", df

The CSV file "test.csv" contains the following data

   x  y  z
0  5  4  4
1  2  1  1
2  1  5  5
3  9 10  0

Output

With headers, the DataFrame is:

     x  y  z
NaN  x  y  z
0.0  5  4  4
1.0  2  1  1
2.0  1  5  5
3.0  9 10  0

Without headers, the DataFrame is:
   x  y  z
0  5  4  4
1  2  1  1
2  1  5  5
3  9 10  0
raja
Published on 14-Sep-2021 12:15:25
Advertisements