【问题标题】:How to find duplicate values and corresponding value into new columns如何在新列中查找重复值和对应值
【发布时间】:2020-05-07 07:15:50
【问题描述】:

我有这样的数据框,其中国家和名称对于同一 ID 来说是唯一的,必须在新列中。

预期输出: 如果值是重复的,不需要在新列中显示,则可以为空

尝试使用下面的代码,但如果我将 2 列放在一起并执行相同的任务,一列可以正常工作。

group = df.groupby('ID')
df1 = group.apply(lambda x:x['COUNTRY'].unique())
df1=df1.apply(pd.Series)

【问题讨论】:

    标签: python python-3.x pandas jupyter-notebook jupyter


    【解决方案1】:

    您可以执行以下操作,

    # Create a dataframe where each element is aggregated as list
    new_df = df.groupby('ID').agg(lambda x: pd.Series(x).unique().tolist())
    
    # Generate column names to be used after expanding lists
    country_cols = ['Country_'+str(i) for i in range(new_df["Country"].str.len().max())]
    name_cols = ['Name_'+str(i) for i in range(new_df["Name"].str.len().max())]
    
    # Drop the Country, Name columns from the original and expand Country, Name columns and concat that to the original dataframe, finally do a fillna
    df2 = pd.concat(
        [new_df.drop(['Country','Name'], axis=1), 
         pd.DataFrame.from_records(new_df["Country"], columns=country_cols, index=new_df.index),
         pd.DataFrame.from_records(new_df["Name"], columns=name_cols, index=new_df.index)
         ], axis=1
         ).fillna(' ')
    
    

    【讨论】:

    • 我收到如下错误。 TypeError:参数“行”的类型不正确(预期列表,得到系列)
    • @Karthike 你能告诉我你在哪一行出错了吗?
    【解决方案2】:

    我们可以用一个简单的函数来做到这一点:

    def unique_column_unstack(dataframe,agg_columns):
        dfs = []
        for col in agg_columns:
            agg_df = df.groupby('ID')[col].apply(lambda x : pd.Series(x.unique().tolist())).unstack()        
            agg_df.columns = agg_df.columns.map(lambda x : f"{col}_{x+1}")
            dfs.append(agg_df)
        return pd.concat(dfs,axis=1)
    

    new_df = unique_column_unstack(df,['COUNTRY','NAME'])
    
    print(new_df)
    
           COUNTRY_1 COUNTRY_2 NAME_1 NAME_2
    ID                                      
    20_001        US        IN    LIZ    LAK
    20_002        US       NaN    LIZ   CHRI
    20_003        US        EU    LIZ    NaN
    20_004        EU       NaN   CHRI    NaN   
    

    【讨论】:

    • @Karthike 没问题,如果它解决了您的问题,请在此答案上打勾,以便关闭。
    猜你喜欢
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 2021-01-26
    相关资源
    最近更新 更多