说我有一个数据帧,看起来像:
Name Group_Id
AAA 1
ABC 1
CCC 2
XYZ 2
DEF 3
YYH 3
我怎么能随意选择每个Group_Id
一个(或多个)排?说,我想每一个Group_Id
随机抽签,我会得到:
Name Group_Id
AAA 1
XYZ 2
DEF 3
size = 2 # sample size
replace = True # with replacement
fn = lambda obj: obj.loc[np.random.choice(obj.index, size, replace),:]
df.groupby('Group_Id', as_index=False).apply(fn)
从0.16.x
起pd.DataFrame.sample
提供了一种方法,以从物体的轴返回的项的随机样本。
In [664]: df.groupby('Group_Id').apply(lambda x: x.sample(1)).reset_index(drop=True)
Out[664]:
Name Group_Id
0 ABC 1
1 XYZ 2
2 DEF 3
在一个优雅的一个衬垫使用GROUPBY和random.choice:
df.groupby('Group_Id').apply(lambda x :x.iloc[random.choice(range(0,len(x)))])
有两种方法可以做到这一点很简单,一个没有用,除了基本的语法大熊猫什么:
df[['x','y']].groupby('x').agg(pd.DataFrame.sample)
这需要14.4ms有5万的行数据集。
另外,稍快的方法,包括numpy的。
df[['x','y']].groupby('x').agg(np.random.choice)
这需要10.9ms用(下同)5万的行数据集。
一般来说,使用熊猫的时候,它的最好坚持使用其母语的语法。特别是对于初学者。
随机选择每组试df.sample(frac = 1.0).groupby('Group_Id').head(1)
只有一行
使用random.choice
,你可以这样做:
import random
name_group = {'AAA': 1, 'ABC':1, 'CCC':2, 'XYZ':2, 'DEF':3, 'YYH':3}
names = [name for name in name_group.iterkeys()] #create a list out of the keys in the name_group dict
first_name = random.choice(names)
first_group = name_group[first_name]
print first_name, first_group
random.choice(seq)
Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.
您可以使用pandas.groupby
,pandas.concat
和random.sample
的组合:
import pandas as pd
import random
df = pd.DataFrame({
'Name': ['AAA', 'ABC', 'CCC', 'XYZ', 'DEF', 'YYH'],
'Group_ID': [1,1,2,2,3,3]
})
grouped = df.groupby('Group_ID')
df_sampled = pd.concat([d.ix[random.sample(d.index, 1)] for _, d in grouped]).reset_index(drop=True)
print df_sampled
输出:
Group_ID Name
0 1 AAA
1 2 XYZ
2 3 DEF