Writing multiple csv's from a function [closed]

巧了我就是萌 提交于 2019-12-23 04:49:10

问题


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.

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']

which would output 3 different .csv's: Ben.csv, Steve.csv, Mary.csv.


回答1:


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?

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

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



回答2:


This seems to be what you're looking for:

import pandas as pd

df = pd.DataFrame({'name': ['Ben','Steve','Mary','Ben','Steve','Mary'], 'value': [1,2,3,4,5,6]})

def write_custom_csv(name):
    filtered = df[df['name'] == name]
    filtered.to_csv(name + '.csv')

You just pass whatever name as name in the function, and the function will filter the global pandas.DataFrame called df based on the passed name. Then that "filtered" DataFrame is written to file.



来源:https://stackoverflow.com/questions/42476413/writing-multiple-csvs-from-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!