Cameron
Cameron

Reputation: 99

Changing Column Heading CSV File

I am currently trying to change the headings of the file I am creating. The code I am using is as follows;

import pandas as pd
import os, sys
import glob
path = "C:\\Users\\cam19\\Desktop\\Test1\\*.csv"
list_=[]
for fname in glob.glob(path):
    df = pd.read_csv(fname, dtype=None, low_memory=False)
    output = (df['logid'].value_counts())
    list_.append(output)
    df1 = pd.DataFrame()
    df2 = pd.concat(list_, axis=1)
    df2.to_csv('final.csv')

Basically I am looping through a file directory and extracting data from each file. Using this is outputs the following image; https://i.sstatic.net/roER1.jpg

All i want to do it change the columns names from 'logid' to the file name it is currently searching but I am not sure how to do this. Any help is great! Thanks.

Upvotes: 0

Views: 1237

Answers (1)

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

Instead of appending the values try to append values by creating the dataframe and setting the column i.e

output = pd.DataFrame(df['value'].value_counts())
output.columns = [os.path.basename(fname).split('.')[0]]
list_.append(output)

Changes in the code in the question

import pandas as pd
import os, sys
import glob
path = "C:\\Users\\cam19\\Desktop\\Test1\\*.csv"
list_=[]

for fname in files:
    df = pd.read_csv(fname)
    output = pd.DataFrame(df['value'].value_counts())
    output.columns = [os.path.basename(fname).split('.')[0]]
    list_.append(output)


df2 = pd.concat(list_, axis=1)
df2.to_csv('final.csv')

Hope it helps

Upvotes: 2

Related Questions