【问题标题】:Delete rows based on unique number of elements in a column pandas [duplicate]根据熊猫列中元素的唯一数量删除行[重复]
【发布时间】:2020-03-26 01:22:11
【问题描述】:

给定一个包含两列 AB 的数据框:

df = 

A      B
cat    3
cat    4
cat    2
bird   1
bird   3
bird   2
bird   5
bird   3

如果A 列中唯一元素的数量少于3,我想删除行 cat 的 len 为 - 3(删除) bird 的 len 为 - 5(保持)

想要的输出:

df = 

A      B
bird   1
bird   3
bird   2
bird   5
bird   3

【问题讨论】:

标签: python pandas numpy


【解决方案1】:

此问题与Python: Removing Rows on Count condition重复


我确定有更好的方法,只是我还没有完全找到它。我会继续寻找。

import pandas as pd

raw_str = \
'''
A      B
cat    3
cat    4
cat    2
bird   1
bird   3
bird   2
bird   5
bird   3'''

df_1 = pd.read_csv(StringIO(raw_str), delim_whitespace=True, header=0, dtype={'A': str, 'B': int})


val_counts = df_1['A'].value_counts()

df_1 = df_1[(val_counts[df_1['A']] > 3).reset_index(drop=True)]

【讨论】:

    【解决方案2】:

    使用filter:

    result = df.groupby('A').filter(lambda x: len(x) > 3)
    print(result)
    

    输出

          A  B
    3  bird  1
    4  bird  3
    5  bird  2
    6  bird  5
    7  bird  3
    

    您也可以使用value_counts:

    # find the count by each value of A
    counts = df.A.value_counts().to_frame()
    
    # keep those with count above 3
    keep = counts[counts.A > 3].index
    
    # filter
    result = df[df.A.isin(keep)]
    print(result)
    

    【讨论】:

      猜你喜欢
      • 2021-12-02
      • 2019-04-19
      • 2021-04-14
      • 2017-10-04
      • 1970-01-01
      • 1970-01-01
      • 2015-11-07
      • 1970-01-01
      • 2021-11-02
      相关资源
      最近更新 更多