【问题标题】:Groupby and keep only groups that contain values within a listGroupby 并仅保留包含列表中值的组
【发布时间】:2020-06-02 09:16:28
【问题描述】:

你好,我有一个 df,例如

list_vales_regex=['ABC',DEF']
Groups Names
G1 ABC_9
G1 ZTY_2
G1 SGG56
G1 BBCHU
G1 DEFE_8
G2 ABC_6
G2 GGDY
G3 ABC_6
G3 DEF98
G3 DEF89
G4 DEF_09
G4 DGE7
G5 DGGE22
G5 DGGE23

我想只保留包含两者(ABC 和 DEF 名称)的组

这里的例子中只有G1 和G3 没有被保留。 有人有想法吗?

【问题讨论】:

    标签: python regex pandas dataframe


    【解决方案1】:

    首先通过Series.str.extract 与| 将值按列表获取到帮助器Series 的值,以连接正则表达式or 的值,然后比较GroupBy.transform 中每个组转换为sets 的值:

    list_vales_regex=['ABC','DEF']
    
    s = df['Names'].str.extract(f'({"|".join(list_vales_regex)})', expand=False)
    df = df[s.groupby(df['Groups']).transform(lambda x: set(x) >= set(list_vales_regex))]
    print (df)
      Groups   Names
    0     G1   ABC_9
    1     G1   ZTY_2
    2     G1   SGG56
    3     G1   BBCHU
    4     G1  DEFE_8
    7     G3   ABC_6
    8     G3   DEF98
    9     G3   DEF89
    

    或者通过GroupBy.transform 和DataFrameGroupBy.nunique 过滤(如果不是大数据,因为速度较慢):

    df = df[s.groupby(df['Groups']).transform('nunique').ge(2)]
    

    另一种方法是找到groups 与np.logical_and.reduce 匹配列表理解中的所有列表值,以测试Series.any 是否匹配至少一个值,然后通过L[0] 按列表的第一个值过滤组并通过给Series.isin:

    list_vales_regex=['ABC','DEF']
    
    L = [df.set_index('Groups')['Names'].str.contains(x).any(level=0) for x in list_vales_regex]
    
    df = df[df['Groups'].isin(L[0].index[np.logical_and.reduce(L)])]
    print (df)
      Groups   Names
    0     G1   ABC_9
    1     G1   ZTY_2
    2     G1   SGG56
    3     G1   BBCHU
    4     G1  DEFE_8
    7     G3   ABC_6
    8     G3   DEF98
    9     G3   DEF89
    

    详情:

    print (np.logical_and.reduce(L))
    [ True False  True False False]
    
    print (L[0].index[np.logical_and.reduce(L)])
    Index(['G1', 'G3'], dtype='object', name='Groups')
    

    【讨论】:

    • 我们可以这样做:df.loc[s.groupby(df['Groups']).transform('nunique').ge(2)]
    • @ansev - 超级或类似df = df[s.groupby(df['Groups']).transform('nunique').ge(2)]
    猜你喜欢
    • 2021-07-25
    • 2021-05-14
    • 2023-02-09
    • 2020-12-13
    • 2022-10-12
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    相关资源
    最近更新 更多