【问题标题】:eliminate duplicate row in dataframe and keep the row with specific string value消除数据框中的重复行并保留具有特定字符串值的行
【发布时间】:2019-01-11 10:43:01
【问题描述】:
import pandas as pd 

dfa = {'account':['a','b','a','c','a'],
      'ret_type':['CTR','WO','T','CTR','T'],
      'val':['0.0','0.1','0.2','0.3','0.4'],
      'ins_date':['11','12','11','13','14']}
df = pd.DataFrame(dfa)

    account ret_type     val    ins_date
0     a       CTR        0.0    11
1     b       WO         0.1    12
2     a       T          0.2    11
3     c       CTR        0.3    13
4     a       T          0.4    14

我有一个要求,我需要消除重复的行,这样

1 duplicate row means combination of (account,ins_dat) 
2 if duplicate found i need to keep row with ret type CTR abd drop row with T
3 i dont want to delete T rows for which no duplicate row is there like 4
4 in this example fr ex 2nd row is deleted as output finally

我该怎么做?

【问题讨论】:

  • 期望的输出是什么?把它贴出来,这样会很容易阅读。
  • 如第 4 行所述,所需输出为 df 没有第 2 行 a T 0.2 11
  • 基于account, return_type,ins_dat 的组合,您的示例中没有重复项。你能补充一些吗?
  • 对不起,仅基于帐户和ins_date
  • df.drop_duplicates(subset = ['account', 'ins_date']) ?

标签: python python-3.x pandas dataframe data-science


【解决方案1】:

请检查这个。你会得到答案的。

df["duplicated"] = df[["account", "ins_date"]].duplicated(keep=False)
df = df[(df.ret_type == 'CTR') | ~df["duplicated"]]

【讨论】:

  • 伟大的。也更快。 +1
  • 是的 df = pd.DataFrame(dfa) df["duplicate"] = df[["account", "ins_date"]].duplicated(keep=False) print(df) df1 = df .loc[(df['ret_type']=='T') & (df['duplicate'] == True) ] df = df[~df.isin(df1)].dropna() df
  • "AlarmName" : {"Fn::Join" : ["", [ {"Ref" : "AppId"}, ",", {"Ref" : "AppServerAG"}, " :", "HealthCheck", ",", "MAJOR"]]},
【解决方案2】:

我不确定我是否理解你:

>>> df.drop_duplicates(subset = ['account', 'ins_date'])
  account ret_type  val ins_date
0       a      CTR  0.0       11
1       b       WO  0.1       12
3       c      CTR  0.3       13
4       a        T  0.4       14

【讨论】:

  • 这行不通,因为我需要使用 ret_typ CTR 而不是 T 保留该行。如果我先得到一个 ret 类型的 T 行,那么它将保留它
  • 那么,它与 True /False 布尔列有什么区别?
【解决方案3】:

您可以使用循环并检查重复项

account 和 ret_type 组合图

--- 然后使用索引删除该行。

map ={}

for index, row in df.iterrows():
    if(map[row['account']]):
        if(map[row['account']] == row['ret_type']):
            df.drop(df.index[index])
    else:
        map[row['account']] = row['ret_type']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 2021-02-19
    • 2019-11-12
    • 2014-12-23
    • 1970-01-01
    相关资源
    最近更新 更多