如何为数据框中的每一列创建一个csv文件? [英] How to create a csv file for each column in a dataframe?
问题描述
我在VSCode中使用Python.我读取了一个CSV文件,并将其转换为用于股票市场收盘价的数据框.第一列是日期列,其他各是股票代码的收盘价.我想将具有多个列的数据框拆分为单独的.csv文件.每个新的.csv文件将按照每个股票代码列标题的名称来命名.
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.
下面是数据框的链接作为示例(原始文件具有500个coluns和10,000行):
Below is a link for the dataframe as example (the original file has like 500 coluns and 10,000 rows):
因此,每个新的.csv文件都将被命名为"TAEE11.csv"
,依此类推,在该列下包含相应的值,并保留"Date".每个文件的列.我想将这些新创建的.csv文件保存到新文件夹(例如,当您在VSCode中使用Python时,可以使用 *.to_csv
将这些新的.csv文件保存到新文件夹)./p>
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
).
推荐答案
- 因为您已经有一个数据框
- 将数据框的索引设置为
日期"
列 - 遍历每列并将其保存到csv.
- 使用
df [col]
为每一列选择数据 - csv文件名将为
f'{col} .csv'
,其中col
是列名. - 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. -
df.to_csv(os.getcwd()+'\\ file.csv')
进入AppData
文件夹 - 当前工作目录不一定是您想要保存文件的位置.
- 指定完整的所需保存路径,例如
'c:/Users/<< user_name>>/Documents/{col} .csv'
. 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)
这篇关于如何为数据框中的每一列创建一个csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Select the data for each column with
- 使用