如何在Pandas数据框中选择值多次出现的行 [英] How to select rows in Pandas dataframe where value appears more than once
本文介绍了如何在Pandas数据框中选择值多次出现的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说,我有Pandas数据框,其中的列具有不同的测量属性和相应的测量值.
Let's say I have the Pandas dataframe with columns of different measurement attributes and corresponding measurement values.
ID Parameter Value
0 'A' 4.3
1 'B' 3.1
2 'C' 8.9
3 'A' 2.1
4 'A' 3.9
. . .
. . .
. . .
100 'B' 3.8
如何过滤此数据框,使其仅显示出现超过X次的测量值?例如,对于此数据框,我想获取所有具有5个以上测量值的行(假设仅参数"A"和"B"出现5次以上),以得到如下所示的数据框.
How can I filter this dataframe to only have measurements that appear more than X number of times? For example, for this dataframe I want to get all rows with more than 5 measurements (lets say only parameters 'A' and 'B' appear more than 5 times) to get a dataframe like below.
ID Parameter Value
0 'A' 4.3
1 'B' 3.1
3 'A' 2.1
. . .
. . .
. . .
100 'B' 3.8
推荐答案
您可以使用value_counts
+ isin
-
v = df.Parameter.value_counts()
df[df.Parameter.isin(v.index[v.gt(5)])]
例如,其中K = 2
(获取所有两个以上读数的项目)-
For example, where K = 2
(get all items which have more than 2 readings) -
df
ID Parameter Value
0 0 A 4.3
1 1 B 3.1
2 2 C 8.9
3 3 A 2.1
4 4 A 3.9
5 5 B 4.5
v = df.Parameter.value_counts()
v
A 3
B 2
C 1
Name: Parameter, dtype: int64
df[df.Parameter.isin(v.index[v.gt(2)])]
ID Parameter Value
0 0 A 4.3
3 3 A 2.1
4 4 A 3.9
这篇关于如何在Pandas数据框中选择值多次出现的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文