'dataframe importing column's first value as column name while reading a CSV file

Whenever I read a csv file using pd.read_csv('file_name.csv') that has no column names, the first value is converted to the Column's name. What can be done ( if it can be done ) to rectify the situation by using Python only. Please don't suggest to open file manually and then place column names in it.



Solution 1:[1]

You need to add parameter header and pass None:

df = pd.read_csv('PATH',header=None)

From pandas read_csv:

header : int, list of int, default ‘infer’ Row number(s) to use as the column names, and the start of the data. Default behavior is to infer the column names: if no names are passed the behavior is identical to header=0 and column names are inferred from the first line of the file, if column names are passed explicitly then the behavior is identical to header=None. Explicitly pass header=0 to be able to replace existing names. The header can be a list of integers that specify row locations for a multi-index on the columns e.g. [0,1,3]. Intervening rows that are not specified will be skipped (e.g. 2 in this example is skipped). Note that this parameter ignores commented lines and empty lines if skip_blank_lines=True, so header=0 denotes the first line of data rather than the first line of the file.

Solution 2:[2]

Have you tried

pd.read_csv(file_name, header=None)

or

pd.read_csv(file_name, names=['col1', 'col2'])

Solution 3:[3]

It depends on what your needs are:

  1. If you already know or want to specify your column names, there is no need to use header = None parameter in pd.read_csv(). Here is a demo example :

df = pd.read_csv(file_path, names=['name1', 'name2'])

else just use:

df = pd.read_csv(file_path, header=None)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Prem Kumar Tiwari