[英]Keep percentage of rows of dataframe based on column value
Let's suppose that I have a dataframe like that:假设我有一个这样的数据框:
import pandas as pd
df = pd.DataFrame({'id':['A','A', 'A', 'B','B'], 'value':[2, 4, 6, 3, 4]})
I want to filter this only for id
= A
and keep an x percentage of the rows having id
= A
.我只想过滤
id
= A
并保留 x 具有id
= A
的行的百分比。
For example if x=60% then the dataframe should look like that:例如,如果 x=60% 那么数据框应该是这样的:
col1 col2
0 A 2
1 A 4
2 B 3
2 B 4
How can I do this efficiently in pandas
?我怎样才能在
pandas
有效地做到这一点?
Just to clarify that it is not necessary that all the id
=A rows are the one after each other.只是为了澄清没有必要所有
id
=A 行都是一个接一个。
One way is using iloc[]
with pd.concat
一种方法是将
iloc[]
与pd.concat
一起pd.concat
x = 0.6
cond = df['id'].eq('A')
out = pd.concat((df[cond].iloc[:int(round(df['id'].eq('A').sum() * x))],
df[~cond]),sort=False).sort_index()
id value
0 A 2
1 A 4
3 B 3
4 B 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.