Home > other >  Pandas CSV and Headers - CSV imports first row as actual header. If add a header, it overwrites rath
Pandas CSV and Headers - CSV imports first row as actual header. If add a header, it overwrites rath

Time:08-25

I'm using https://www.stackvidhya.com/how-to-add-header-to-pandas-dataframe/ for reference.

I have a CSV which for some reason, imports the first 'row' as the headers. So if I go to 'add' headers, ie the real headers, it just overwrites the first row.

Is there a way around this?

Code & Examples:

import pandas as pd
nocolumns = pd.read_csv("nocolumns.csv")

nocolumns csv example

#add columns
nocolumns.columns = ["Col1", "Col2", "Col3", "Col4"]

columns added, but overwriting 1st row

how do I add the headers properly without over-writing the first row?

CodePudding user response:

First call header=None, and then assign column names:

nocolumns = pd.read_csv("nocolumns.csv", header=None)
nocolumns.columns = ["Col1", "Col2", "Col3", "Col4"]

CodePudding user response:

You can supply the header and names arguments as so:

nocolumns = pd.read_csv("nocolumns.csv", header=None, names=["Col1", "Col2", "Col3", "Col4"])

  • Related