0

I am using Python in VSCode. I read a CSV file and transformed it in a dataframe for stock market's close prices. First column is date column and others are each stock symbol close prices. I would like to split this dataframe with multiple columns into separate .csv files. Each new .csv file will be named as per each stock symbol column´s header´s name.

Below is a link for the dataframe as example (the original file has like 500 coluns and 10,000 rows):

So, each new .csv file will be named such as "TAEE11.csv" and so on contain the respective values down that column keeping the "Date" column for each file as well. I would like to save these newly created .csv files to a new folder (like when you are using Python inside VSCode you can save these new .csv files to a new folder with *.to_csv).

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158

1 Answers1

2
  • Since you already have a dataframe
  • Set the index of the dataframe as the 'Date' column
  • Iterate through each column and save it to a csv.
    • Select the data for each column with df[col]
    • The csv file name will be f'{col}.csv', where col is the column name.
  • To specify a specific file save location when working in VSCode, see this SO: Answer
    • df.to_csv(os.getcwd()+'\\file.csv') goes into the AppData folder
    • The current working directory is not necessarily where you want the file saved.
    • Specify the full desired save path, 'c:/Users/<<user_name>>/Documents/{col}.csv', for example.
import pandas as pd

# set Date as the index
df.set_index('Date', inplace=True)

# iterate through each column and save it
for col in df.columns:
    df[col].to_csv(f'c:/Users/<<user_name>>/Documents/{col}.csv', index=True)
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158