1

I have plenty of csvs that look like this:

csv output 1

I want to rename column names because they are too long and to insert new column named Company with same values (eg. aapl (ticker for Apple)). Here's the code how I did that:

data = pd.read_csv('aapl.csv', index_col=0)
data.insert(0, 'Company', 'aapl')
data.rename(columns={'Unnamed: 0': 'Company', 'Working Capital / Total Assets':'WC/TA', 'Retained Earnings / Total Assets': 'RE/TA', 'EBIT / Total Assets':'EB/TA','Current Market Cap / Total Liabilites':'MC/TL', 'Revenue / Total Assets':'RV/TA','Net Income / Total Assets (ROA)':'NI/TA', 'Total Liabilites / Total Assets':'TL/TA', 'Current Assets / Current Liabilites':'CA/CL'})
data.to_csv('aapl.csv')

and I get

enter image description here

Thing is, I have 278 other companies in same csv format (imb.csv, ase.csv, wire.csv etc.) and I would like to rename/insert columns for all of them in the same way. Finaly, I need to merge all these csv files into one csv (that is the reason why is new column "Company" needed).

My question is, how to create new column (name: Company) and populate it with name of the file.

For example: load ibm.csv -> rename columns -> add new column (Company) -> insert value ibm (filename/ticker) in column Company -> export to csv.

dejanmarich
  • 1,235
  • 10
  • 26

1 Answers1

2

You can read each file in dict comprehension, add key by name of file and last concat together:

import glob, os

files = glob.glob('files/*.csv')

d = {'Working Capital / Total Assets':'WC/TA', 
     'Retained Earnings / Total Assets': 'RE/TA', 
     'EBIT / Total Assets':'EB/TA',
     'Current Market Cap / Total Liabilites':'MC/TL',
     'Revenue / Total Assets':'RV/TA',
     'Net Income / Total Assets (ROA)':'NI/TA',
     'Total Liabilites / Total Assets':'TL/TA',
     'Current Assets / Current Liabilites':'CA/CL'}

dfs = {os.path.basename(fp).split('.')[0]: pd.read_csv(fp).rename(columns=d) for fp in files}
df = pd.concat(dfs).reset_index(level=1,  drop=True).rename_axis('company').reset_index()
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252