Home > other >  Add header to dataframe to only first 2 columns
Add header to dataframe to only first 2 columns

Time:11-19

I am trying to add header to 2 columns into my dataframe and save it as an CSV. My df has 99 columns but I only want to add the header names to the first 2 columns.

When I try this

import pandas as pd 
import os 


for f in csv_files:
    headers = ['hello','world']

    df = pd.read_csv(f, names = headers, sep = ',')
    df.to_csv(r'~/Documents/hi.csv', index = False, header=True)

This gets the CSV with the headers but only first 2 columns. I still want the rest of the data but no headers on them or any default header would be okay as well.

When I change index = True, it saves the rest of the columns but my headers are on the very last 2 columns of the CSV instead of the first 2, how do I switch them, or make sure they are on the first 2 columns when creating the CSV?

CodePudding user response:

Try this:

index = 0
for f in csv_files:
    df = pd.read_csv(f, sep = ',')
    old_cols = list(df.columns)[2:]
    headers = ['hello','world']
    new_cols = headers   old_cols
    df.columns = new_cols
    df.to_csv(f'./{index}.csv', index = False, header=True)
    index = index   1
  • Related