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).

0

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Dear Trenton! It worked just like a charm! Already checked as requested! If possible I would check many times over! All the best!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.