问题
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