简体   繁体   中英

Modify location for for to_csv function loop in python

I am using the jupyter notebook to write my code. In the end, I want to generate several CSVs based on the value in the REGION column. I know how to do it. But I am not sure how to put all of them in one specific folder (the following code automatically put all new CSVs to the jupyper notebook location. I am trying to put it in a folder in my desktop).

Thanks in advance

    file_name = 'new_{0}.csv'.format(u) 
    df[df['REGION'] == u].to_csv(file_name, sep=',') ```
 

You can do this

import os 
import pandas as pd

path = "" # Path to the folder you wish to keep your file under

for region in df['Region'].unique():
    file_name = os.path.join(path,f'new_{region}.csv')
    df[df['REGION'] == region].to_csv(file_name, sep=',',index=False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM