简体   繁体   English

Pandas:用空白 groupby 替换重复值,例如

[英]Pandas: replace repeated values with blanks groupby like

I got dataframe with columns got groups of repeated values.我得到了带有列的数据框,其中包含重复值组。 What i want is to keep only first item in such columns.我想要的是只保留这些列中的第一项。

I've tried df = df.groupby(['author', 'key']) but don't know how to correctly get all rows.我试过df = df.groupby(['author', 'key'])但不知道如何正确获取所有行。 With df.first() only first rows will be printed.使用df.first()只会打印第一行。

import pandas as pd

lst = [
['juli', 'JIRA-1', 'assignee'],
['juli', 'JIRA-1', 'assignee'],
['nick', 'JIRA-1', 'timespent'], 
['nick', 'JIRA-3', 'status'], 
['nick', 'JIRA-3', 'assignee'],
['tom', 'JIRA-1', 'comment'], 
['tom', 'JIRA-1', 'assignee'], 
['tom', 'JIRA-2', 'status']] 

df = pd.DataFrame(lst, columns =['author', 'key', 'field']) 
#df = df.sort_values(by=['author', 'key'])

>>> df
  author     key      field
0   juli  JIRA-1   assignee
1   juli  JIRA-1   assignee
2   nick  JIRA-1  timespent
3   nick  JIRA-3     status
4   nick  JIRA-3   assignee
5    tom  JIRA-1    comment
6    tom  JIRA-1   assignee
7    tom  JIRA-2     status

what I got:我得到了什么:

>>> df.groupby(['author', 'key']).first()
                   field
author key
juli   JIRA-1   assignee
nick   JIRA-1  timespent
       JIRA-3     status
tom    JIRA-1    comment
       JIRA-2     status

what I want:我想要的是:

juli   JIRA-1   assignee
                assignee
nick   JIRA-1  timespent
       JIRA-3     status
                assignee
tom    JIRA-1    comment
                assignee
       JIRA-2     status

Looks like you need df.duplicated() to find duplicates and df.loc[] to assign blank spaces:看起来你需要df.duplicated()来查找重复项和df.loc[]来分配空格:

df.loc[df.duplicated(['author','key']),['author','key']]=''
print(df)

  author     key      field
0   juli  JIRA-1   assignee
1                  assignee
2   nick  JIRA-1  timespent
3   nick  JIRA-3     status
4                  assignee
5    tom  JIRA-1    comment
6                  assignee
7    tom  JIRA-2     status

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM