【问题标题】:Remove duplicate values while group by in pandas data frame在熊猫数据框中分组时删除重复值
【发布时间】:2021-09-13 10:23:35
【问题描述】:

【问题讨论】:

  • 将数据样本添加为代码 sn-ps 和您想要的输出会有很大帮助:)
  • 数据样本已添加,请查看
  • 添加代码 sn-ps 意味着摆脱图像 ;) @Sandeep Singh

标签: python pandas dataframe pandas-groupby


【解决方案1】:

在将tuple应用于列表之前,您可以使用SeriesGroupBy.unique()获取entity_text的唯一值,如下所示:

(df.groupby("entity_label", sort=False)["entity_text"]
   .unique()
   .apply(tuple)
   .reset_index(name="entity_text")
)

结果:

  entity_label                                                      entity_text
0    job_title  (Full Stack Developer, Senior Data Scientist, Python Developer)
1      country                                     (India, Malaysia, Australia)

【讨论】:

  • 太好了,你解决了我长期悬而未决的问题,向你致敬
  • @SandeepSingh 很高兴为您提供帮助!编程愉快!
【解决方案2】:

试试这个:

import pandas as pd
df = pd.DataFrame({'entity_label':["job_title", "job_title","job_title","job_title", "country", "country", "country", "country", "country"],
'entity_text':["full stack developer", "senior data scientiest","python developer","python developer", "Inida", "Malaysia", "India", "Australia", "Australia"],})
df.drop_duplicates(inplace=True)
df['entity_text'] = df.groupby('entity_label')['entity_text'].transform(lambda x: ','.join(x))
df.drop_duplicates().reset_index().drop(['index'], axis='columns')

输出:

    entity_label    entity_text
0   job_title   full stack developer,senior data scientiest,py...
1   country     Inida,Malaysia,India,Australia

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 2016-10-02
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多