繁体   English   中英

Python:在计数条件下删除行

[英]Python: Removing Rows on Count condition

我在过滤pandas数据框时遇到问题。

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

df.city.value_counts()

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

如果不逐个城市手动删除它们,有什么方法可以做到这一点?

给你带过滤器

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

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

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

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

counts是一个pd.Series对象。 counts < 5返回一个布尔系列。 我们通过布尔counts < 5系列过滤计数系列(这就是方括号实现的功能)。 然后,我们使用结果系列的索引来查找计数小于 5 的城市。 ~是否定运算符。

记住系列是索引和值之间的映射。 系列的索引不一定包含唯一值,但这可以通过value_counts的输出来保证。

我认为您正在寻找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)]

另一种解决方案:

threshold=3
df['Count'] = df.groupby('City')['City'].transform(pd.Series.value_counts)
df=df[df['Count']>=threshold]
df.drop(['Count'], axis = 1, inplace = True)
print(df)

  City
0  NYC
1  NYC
2  NYC
3  NYC

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM