Save grouped by results into separate CSV files

2019-03-04 00:26发布

问题:

I have a code for create groups with CSV data and create new files with that groups too!

I read my csv file and then work with that. The problem is when my funtion works and create the new files with the data, the name of the new files is the name of the group and I don´t want that:

ID           Inventory    Domain                   Requests   Impressions      Fill Rate
123456       au_to/8         neighborhoodscout.com      11402        26            0.23
123456       au_to/8         sinembargo.mx              10334        24            0.23
123456       au_to/8         elsalvadortimes.com        9893         17            0.17
155444       cami_oneta/8    thealternativedaily.com    51389        81            0.16
155444       cami_oneta/8    heywise.com                45578       135            0.3
155444       cami_oneta/8    wis.pr                     28792        69            0.24

To be more clear when I finish the programm, I have a file: 123456/8.csv and another 155444/8.csv and I need to change this name to au_to.csv and cami_oneta.csv. I know maybe I should grup by Inventory instead of ID but the names of Inventoory field have / and _ and I have an error:

AttributeError: 'function' object has no attribute 'join'

Here is my code:

import pandas as pd

df = pd.read_csv("Tags para Mandar WL.csv",  header=0,  sep = ",")
for group in df.groupby.join(df["ID"]):
    group[1].to_csv("{}.csv".format(group[0]), sep=',', index=False)

回答1:

You must specify a groupby clause, so pandas knows what to group by. This should work:

for i, g in df.groupby('Inventory'):
     g.to_csv('{}.csv'.format(i.split('/')[0]), index=False)