将按结果分组的结果保存到单独的CSV文件中 [英] Save grouped by results into separate CSV files

查看:396
本文介绍了将按结果分组的结果保存到单独的CSV文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码,可以使用CSV数据创建组,也可以使用该组创建新文件!

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

我阅读了csv文件,然后进行处理.问题是当我的功能正常工作并使用数据创建新文件时,新文件的名称就是该组的名称,而我不希望这样:

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

为了更清楚地完成编程,我有一个文件:123456/8.csv和另一个155444/8.csv,我需要将此名称更改为au_to.csv和cami_oneta.csv.我知道也许我应该按库存而不是ID进行分类,但是库存字段的名称包含/和_,并且我有一个错误:

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'

这是我的代码:

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)

推荐答案

必须指定groupby子句,所以熊猫知道进行分组.这应该起作用:

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)

这篇关于将按结果分组的结果保存到单独的CSV文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆