我在过滤pandas
数据框时遇到问题。
city
NYC
NYC
NYC
NYC
SYD
SYD
SEL
SEL
...
df.city.value_counts()
我想删除频率小于4的城市行数,例如SYD和SEL。
如果没有逐个城市手动删除它们,会有什么办法呢?
答案 0 :(得分:8)
您可以使用过滤器
df.groupby('city').filter(lambda x : len(x)>3)
Out[1743]:
city
0 NYC
1 NYC
2 NYC
3 NYC
答案 1 :(得分:7)
这是使用pd.Series.value_counts
的一种方法。
counts = df['city'].value_counts()
res = df[~df['city'].isin(counts[counts < 5].index)]
答案 2 :(得分:3)
我认为您正在寻找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)]
答案 3 :(得分:2)
另一种解决方案:
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