python-3.x 将具有不同列值的重复行分组,然后发送到csv

9q78igpj  于 2023-01-27  发布在  Python
关注(0)|答案(2)|浏览(148)

我有这个csv文件favsites.csv

Emails                          Favorite Site                                                                                       
batman@email.com                something.com          
batman@email.com                hamburgers.com         
poisonivy@email.com             yonder.com             
superman@email.com              cookies.com            
catgirl@email.com               cattreats.com           
catgirl@email.com               fishcaviar.com          
catgirl@email.com               elegantfashion.com             
joker@email.com                 cards.com            
supergirl@email.com             nailart.com

我想将重复项分组,然后合并列,然后发送到csv。
因此,分组和合并后,它应该如下所示:

Emails                          Favorite Site                                                                                       
batman@email.com                something.com          
                                hamburgers.com         
poisonivy@email.com             yonder.com             
superman@email.com              cookies.com            
catgirl@email.com               cattreats.com           
                                fishcaviar.com          
                                elegantfashion.com             
joker@email.com                 cards.com            
supergirl@email.com             nailart.com

我怎样把它发送到一个csv文件中,并让它看起来像这样?但是something.comhamburgers.com在一个单元格中表示 bat 侠;而cattreats.comfishcaviar.comelegantfashion.com在一个单元格中,或者,将它们放在同一行但不同的列中,如下图所示。

Emails                          Favorite Site                                                                                       
batman@email.com                something.com    hamburgers.com                                
poisonivy@email.com             yonder.com             
superman@email.com              cookies.com            
catgirl@email.com               cattreats.com    fishcaviar.com   elegantfashion.com             
joker@email.com                 cards.com            
supergirl@email.com             nailart.com

下面是我的代码:

import pandas as pd

Dir='favsites.csv'
sendcsv='mergednames.csv'

df = pd.read_csv(Dir)
df = pd.DataFrame(df)
df_sort = df.sort_values('Emails')
grouped = df_sort.groupby(['Emails', 'Favorite Site']).agg('sum')

分组打印时,显示:

Empty DataFrame
Columns: []
Index: [(batman@email.com, hamburgers.com), (batman@email.com, something.com), (catgirl@email.com, cattreats.com), (catgirl@email.com, elegantfashion.com), (catgirl@email.com, fishcaviar.com), (joker@email.com, cards.com), (poisonivy@email.com, yonder.com), (supergirl@email.com, nailart.com), (superman@email.com, cookies.com)]
idfiyjo8

idfiyjo81#

可以用空字符串替换重复值:

emails = ['batman@email.com', 'poisonivy@email.com','superman@email.com', 'batman@email.com']
favs =['something.com', 'hamburgers.com', 'yonder.com', 'cookies.com' ]
df = pd.DataFrame({'Emails': emails, 'Favorite Site': favs})

df_sorted = df.sort_values('Emails')
df_sorted.loc[df['Emails'].duplicated(), 'Emails'] = ''

输出:
| 电子邮件|收藏网站|
| - ------|- ------|
| batman@email.com | something.com |
| | cookies.com |
| poisonivy@email.com | hamburgers.com |
| superman@email.com | yonder.com |

qcbq4gxm

qcbq4gxm2#

IIUC,您可以将pandas.Series.str.ljustpandas.DataFrame.to_csv与(\t)一起用作 sep

df.loc[df["Emails"].duplicated(), "Emails"] = ""

len_emails = df["Emails"].str.len().max()
len_sites = df["Favorite Site"].str.len().max()

df = df.T.reset_index().T.reset_index(drop=True)

df[0] = df[0].str.ljust(len_emails)
df[1] = df[1].str.ljust(len_sites)

df.to_csv("/tmp/out1.csv", index=False, header=False, sep="\t")

输出(* 记事本 *):

对于第二种格式,可以使用pandas.DataFrame.groupby

df = (
        pd.read_csv("/tmp/input.csv", sep="\s\s+", engine="python")
            .groupby("Emails", as_index=False, sort=False).agg(",".join)
            .T.reset_index().T.reset_index(drop=True)
            .pipe(lambda d: d[[0]].join(d[1].str.split(",", expand=True), rsuffix="_"))
            .pipe(lambda d: pd.concat([d[col].str.ljust(d[col].fillna("").str.len().max().sum())
                for col in d.columns], axis=1))
    )
    
df.to_csv('tmp/out2.csv', index=False, header=False, sep="\t")

输出(* 记事本 *):

相关问题