从一个函数编写多个csv [英] Writing multiple csv's from a function
问题描述
假设我有一个根据某些变量名称"创建pd.DataFrame的函数:
Let's say that I have a function which creates a pd.DataFrame according to some variable 'name':
def function(name):
...
...
...
return(DataFrame(name)) #parenthesis
#here only to show that the DataFrame will be
#different when a different name is given as input.
我的问题是:我该如何编写一个函数来为名称"的每个可能值编写一个.csv(具有唯一名称)?
My question is: how can I write a function to write a .csv (with a unique name) for each possible value for 'name'?
例如,名称"可能属于列表:
For example, 'name' could belong to the list:
example=['Ben','Steve','Mary']
这将输出3个不同的.csv:Ben.csv,Steve.csv,Mary.csv.
which would output 3 different .csv's: Ben.csv, Steve.csv, Mary.csv.
推荐答案
很抱歉,但是我不确定您的问题:您是否要在数据框中写入具有相同数据的其他CSV文件(无论它来自您的函数),还是要获取数据框,请提取与名称相关联的数据(即在col中),然后将其写入特定的输出CSV文件?
I'm sorry, but I'm not completely sure about your question: do you want to write a different CSV with the same data in the dataframe (whatever it comes from your function), or to get the dataframe, extract the data associated by the name (ie in a col) and then write it to an specific output CSV file?
如果您只想获取数据框并将其写入不同的CSV文件,则一点都不困难:
If you just want to take the dataframe and write it to different CSV files, it's not difficult at all:
for name in ['Ben', 'Steve', 'Mary']:
pd.to_csv('.'.join([name, 'csv']), delimiter=',', encoding='utf-8')
如果您想从给定名称的Dataframe中提取列(从内存中,我可能是错误的):
If you would like to extract the column from the Dataframe given the name (from memory, I could be wrong):
for name in ['Ben', 'Steve', 'Mary']:
user_data = df[[name]] # This will create a copy dataframe.
user_data.to_csv('.'.join([name,'csv']), delimiter=',', encoding='utf-8')
这篇关于从一个函数编写多个csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!