本文介绍了在pandas groupby之后对每组进行采样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这一定在某些地方得到了回答,但我就是找不到.
I know this must have been answered some where but I just could not find it.
问题:groupby操作后对每组进行采样.
Problem: Sample each group after groupby operation.
import pandas as pd
df = pd.DataFrame({'a': [1,2,3,4,5,6,7],
'b': [1,1,1,0,0,0,0]})
grouped = df.groupby('b')
# now sample from each group, e.g., I want 30% of each group
推荐答案
应用 lambda 并调用 sample
带有参数 frac
:
Apply a lambda and call sample
with param frac
:
In [2]:
df = pd.DataFrame({'a': [1,2,3,4,5,6,7],
'b': [1,1,1,0,0,0,0]})
grouped = df.groupby('b')
grouped.apply(lambda x: x.sample(frac=0.3))
Out[2]:
a b
b
0 6 7 0
1 2 3 1
这篇关于在pandas groupby之后对每组进行采样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!