2016-01-21 30 views
1

从熊猫数据帧列低计数我有以下熊猫数据帧:去除条件

new = pd.Series(np.array([0, 1, 0, 0, 2, 2])) 
df = pd.DataFrame(new, columns=['a']) 

I输出的出现的每个值的条件:

print df['a'].value_counts() 

然后,我有以下内容:

0 3 
2 2 
1 1 
dtype: int64 

现在我想删除列'a'值小于2的行。我可以遍历每个值e在df ['a']中并且如果其值计数小于2则将其删除,但是对于具有多个列的大数据帧来说花费很长时间。 我不明白什么是有效的方法来做到这一点。

回答

0

一种方法是将计数数据与原始df相加。

df2 = pd.DataFrame(df['a'].value_counts()) 
df2.reset_index(inplace=True) 
df2.columns = ['a','counts'] 

# df2 = 
# a counts 
# 0 0 3 
# 1 2 2 
# 2 1 1 

df3 = df.merge(df2,on='a') 

# df3 = 
# a counts 
# 0 0 3 
# 1 0 3 
# 2 0 3 
# 3 1 1 
# 4 2 2 
# 5 2 2 

# filter 
df3[df3.counts>=2] 
1

你可以指定你子集的value_counts有那么你的条件获取Series那么指数与isin你可以检查它应该是在原始,然后将值传递给原来的数据框的值:

s = df['a'].value_counts() 
df[df.isin(s.index[s >= 2]).values] 

工作原理:

In [133]: s.index[s >= 2] 
Out[133]: Int64Index([0, 2], dtype='int64') 


In [134]: df.isin(s.index[s >= 2]).values 
Out[134]: 
array([[ True], 
     [False], 
     [ True], 
     [ True], 
     [ True], 
     [ True]], dtype=bool) 


In [135]: df[df.isin(s.index[s >= 2]).values] 
Out[135]: 
    a 
0 0 
2 0 
3 0 
4 2 
5 2