How To Create A Csv File For Each Column In A Dataframe?
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
Solution 1:
- 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'
, wherecol
is the column name.
- Select the data for each column with
- To specify a specific file save location when working in VSCode, see this SO: Answer
df.to_csv(os.getcwd()+'\\file.csv')
goes into theAppData
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)
Post a Comment for "How To Create A Csv File For Each Column In A Dataframe?"