首页 > 解决方案 > 如何在 pandas 中列的值计数条件下采用相同的 DataFrame?

问题描述

我有一个pandas DataFrame,shape(1000,8)所以我想制作新的DataFrame,但在一列中有条件但不是一个简单的条件,它是特定行上的值计数,例如我们有一列df.column1 = [1,2,2,2,3,3,4,5,8,8,8,8]我有相同的DataFrame使用相同的列但在column1上有条件,我只想要column1的值重复超过3次的行,所以我得到:df.column1 = [8,8,8,8]

标签: pythonpandasjupyter-notebook

解决方案


您可以value_counts只使用和保留最常用的值

import pandas as pd
# define df
df = pd.DataFrame()
df['column1'] = [1,2,2,2,3,3,4,5,8,8,8,8] 

#get counts
counts = df['column1'].value_counts()

# keep only counts>3
counts = counts[counts>3]

# get the index to see which column1 values should be kept
to_keep = counts.index

# filter df with only correct values of column1
df.loc[df['column1'].isin(to_keep)]

#   column1
#8  8
#9  8
#10 8
#11 8

推荐阅读