【问题标题】:Save grouped by results into separate CSV files按结果分组保存到单独的 CSV 文件中
【发布时间】:2018-03-15 08:05:30
【问题描述】:

我有一个代码可以用 CSV 数据创建组并用这些组创建新文件!

我阅读了我的 csv 文件,然后使用它。问题是当我的功能正常工作并使用数据创建新文件时,新文件的名称是组的名称,我不希望这样:

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。我知道也许我应该按 Inventory 而不是 ID 进行分组,但是 Inventoory 字段的名称有 / 和 _ 并且我有一个错误:

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)

【问题讨论】:

    标签: python pandas csv group-by pandas-groupby


    【解决方案1】:

    必须指定groupby 子句,这样pandas 就知道什么要分组了。这应该有效:

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

    【讨论】:

      猜你喜欢
      • 2018-11-22
      • 2019-03-25
      • 2019-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      • 1970-01-01
      • 2014-02-20
      相关资源
      最近更新 更多