简体   繁体   中英

How do I convert a for loop to a vector and write that to a csv?

I have created a for loop which extracts all my files from my path and prints the same. I wanted to put this entire functions output into a dataframe and write it to a csv. I know we can do this in R by creating a vector but how do we do it in python?

import pandas
import glob

for filepath in glob.iglob('*.csv'):
    fl = pandas.read_csv(filepath);
    fl.insert(25,'city',filepath)
    print(fl.groupby('city').mean())

Your f1 variable is already a DataFrame. To output it into a csv file on the same directory just use the to_csv methond from pandas.DataFrame.

f1.to_csv('filename.csv')

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