【问题标题】:Add two or more rows according to the some condition [duplicate]根据某些条件添加两行或多行[重复]
【发布时间】:2021-11-03 10:58:26
【问题描述】:

我有一个这样的数据框:

我想将行与名称合并,并根据名称列合并类别。我的意思是如果名称列行具有相同的名称,那么合并类别数据和其余数据将是相同的:

我想要的输出是这样的:

目标是按名称去重复,并将类别列数据合并为一列

【问题讨论】:

    标签: python excel pandas dataframe numpy


    【解决方案1】:

    更新 多列代码:

    df = pd.DataFrame({'Name':["Call Building & Property Maintenance Ltd", "Call Building & Property Maintenance Ltd"],
    'Category':['Fibreglass Roofing', 'Chimney Repairs'], 'Another_column':['Fibreglass Roofing', 'Chimney Repairs']})
    df[['Category', 'Another_column']] = df.groupby('Name')[['Category', 'Another_column']].transform(lambda x: ','.join(x))
    df.drop_duplicates()
    

    输出:

        Name    Category    Another_column
    0   Call Building & Property Maintenance Ltd    Fibreglass Roofing,Chimney Repairs  Fibreglass Roofing,Chimney Repairs
    

    【讨论】:

    • 这行得通,但如果我们有更多的列,我们该怎么做?
    • 答案已更新! @哈里斯艾哈迈德
    猜你喜欢
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多