如何在 Pandas 数据框中选择值出现多次的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48628417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select rows in Pandas dataframe where value appears more than once
提问by Char
Let's say I have the Pandas dataframe with columns of different measurement attributes and corresponding measurement values.
假设我有 Pandas 数据框,其中包含不同测量属性和相应测量值的列。
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
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.
如何过滤此数据框以仅包含出现次数超过 X 次的测量值?例如,对于这个数据框,我想要获得超过 5 个测量值的所有行(假设只有参数 'A' 和 'B' 出现超过 5 次)以获得如下所示的数据框。
ID Parameter Value
0 'A' 4.3
1 'B' 3.1
3 'A' 2.1
. . .
. . .
. . .
100 'B' 3.8
回答by cs95
You can use value_counts
+ isin
-
您可以使用value_counts
+ isin
-
v = df.Parameter.value_counts()
df[df.Parameter.isin(v.index[v.gt(5)])]
For example, where K = 2
(get all items which have more than 2 readings) -
例如,where K = 2
(获取具有超过 2 个读数的所有项目)-
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
回答by jezrael
Use transform
+ size
with boolean indexing
:
使用transform
+size
与boolean indexing
:
df[df.groupby('Parameter')['Parameter'].transform('size') > 5]
回答by YOBEN_S
By using filter
通过使用 filter
df.groupby('Parameter').filter(lambda x : x['Parameter'].shape[0]>=5)
回答by Esptheitroad Murhabazi
Loc with count could also work
带有计数的 Loc 也可以工作
df.loc[df.Parameter.isin((df.groupby('Parameter').size().Value >= 5).index)]