Python:按计数条件移除行

2024-04-28 11:41:53 发布

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

过滤数据帧时出现问题。

city 
NYC 
NYC 
NYC 
NYC 
SYD 
SYD 
SEL 
SEL
...

df.city.value_counts()

我想删除计数频率小于4的城市行,例如SYD和SEL。

如果不用人工逐城投放,怎么办?


Tags: 数据citydfvalue人工频率计数nyc
3条回答

这是一种使用pd.Series.value_counts的方法。

counts = df['city'].value_counts()

res = df[~df['city'].isin(counts[counts < 5].index)]

我想你在找value_counts()

# Import the great and powerful pandas
import pandas as pd

# Create some example data
df = pd.DataFrame({
    'city': ['NYC', 'NYC', 'SYD', 'NYC', 'SEL', 'NYC', 'NYC']
})

# Get the count of each value
value_counts = df['city'].value_counts()

# Select the values where the count is less than 3 (or 5 if you like)
to_remove = value_counts[value_counts <= 3].index

# Keep rows where the city column is not in to_remove
df = df[~df.city.isin(to_remove)]

给你过滤器

df.groupby('city').filter(lambda x : len(x)>3)
Out[1743]: 
  city
0  NYC
1  NYC
2  NYC
3  NYC

解决方案二transform

sub_df = df[df.groupby('city').city.transform('count')>3].copy() 
# add copy for future warning when you need to modify the sub df

相关问题 更多 >