基于分类列中dinstict值的计数,从dataframe中删除所有行

2024-06-16 09:38:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我用过很多列的cars数据框。如果我计算某个制造商的外观:

carsDF.manufacturer.value_counts()

结果如下:

 VW               2228
 Opel             1414
 Renault          1362
 Audi              895
 BMW               888
 Mercedes-Benz     786

如果某个制造商的外观总数小于某个数字,如何从该制造商的数据帧中删除所有行


Tags: 数据valuecarsmercedes外观vwcountsaudi
2条回答

这里有一种方法使用值计数结果上的loc来过滤那些超过最小计数值的制造商

# Sample data.
df = pd.DataFrame(
    {'manufacturer': 
        ['VW'] * 2228 
        + ['Opel'] * 1414 
        + ['Renault'] * 1362
        + ['Audi'] * 895
        + ['BMW'] * 888
        + ['Mercedes-Benz'] * 787}
)

解决方案:

min_count = 1000
main_manufacturers = set(
    df['manufacturer'].value_counts(sort=False).loc[lambda x: x >= min_count].index)
df = df.loc[df['manufacturer'].isin(main_manufacturers)]

你可以做一个地图:

# get the count for each manufacturer
counts = carsDF.manufacturer.value_counts()

# threshold
thresh = 1000

# replace the manufacturer with the counts and thresholding
carsDF[carsDF.manufacturer.map(counts).ge(thresh)]

相关问题 更多 >