Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

dataframe - Repeat the task of exporting multiple Panda datames into multiple csv-files

I'm somewhat new to Pandas/Python (more into SAS), but my task is the following: I have four Pandas dataframes, and I would like to export each of them into a separate csv-file. The name of the csv should be the same as the original dataframe (forsyning.csv, inntak.csv etc).

So far I've made a list with the names of the dataframes, and then tried to put the list through a for-loop in order to generate one csv after another. But I've only made it half-way through. My code so far:

df_list = ['forsyning', 'inntak', 'behandling', 'transport']

for i in df_list:  
    i.to_csv('{}.csv'.format(i), index=False, decimal=',', sep=';')

What I believe is missing is a proper reference where it says "i.to_csv" in my code above as it now only give me the error "'str' object has no attribute 'to_csv'". I justs don't know how to twist this code the right way - appreciate any advice in this matter. Thanks.

question from:https://stackoverflow.com/questions/65916809/repeat-the-task-of-exporting-multiple-panda-datames-into-multiple-csv-files

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If need write list of DataFrames to files you need 2 lists - first for DataFrames objects and second for new file names in strings:

df_list = [forsyning, inntak, behandling, transport]
names   = ['forsyning', 'inntak', 'behandling', 'transport']

So for write use zip of both lists and write df:

for i, df in zip(names, df_list):  
    df.to_csv('{}.csv'.format(i), index=False, decimal=',', sep=';')

Or use dictionary of DataFrames and loop values by dict.items():

df_dict = {'forsyning': forsyning, 'inntak':inntak,
            'behandling': behandling, 'transport': transport}

for i, df in df_dict.items():  
    df.to_csv('{}.csv'.format(i), index=False, decimal=',', sep=';')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...