我有一个简单的df,它形成了一个pivot_table:
d = {'one' : ['A', 'B', 'B', 'C', 'C', 'C'], 'two' : [6., 5., 4., 3., 2., 1.], 'three' : [6., 5., 4., 3., 2., 1.], 'four' : [6., 5., 4., 3., 2., 1.]}
df = pd.DataFrame(d)
pivot = pd.pivot_table(df,index=['one','two'])我想从每个不同的元素中随机抽取1行,这些元素来自于得到的pivot对象中的“one”列。(在本例中,'A‘将始终被采样,而'B’和‘C’有更多的选项。)我刚开始使用0.18.0版本的熊猫,我知道.sample方法。我处理了应用抽样函数的.groupby方法,如下所示:
grouped = pivot.groupby('one').apply(lambda x: x.sample(n=1, replace=False))当我尝试这个主题的变体时,我提出了一个KeyError,所以我认为是时候对这个看似简单的问题提出一些新的观点了……
谢谢你的帮助!
发布于 2016-05-25 04:43:55
引发KeyError的原因是,“one”不是pivot中的列,而是索引的名称:
In [11]: pivot
Out[11]:
four three
one two
A 6.0 6.0 6.0
B 4.0 4.0 4.0
5.0 5.0 5.0
C 1.0 1.0 1.0
2.0 2.0 2.0
3.0 3.0 3.0您必须使用level参数:
In [12]: pivot.groupby(level='one').apply(lambda x: x.sample(n=1, replace=False))
Out[12]:
four three
one one two
A A 6.0 6.0 6.0
B B 4.0 4.0 4.0
C C 1.0 1.0 1.0这是不完全正确的,因为索引是重复的!用as_index=False稍微好一点
In [13]: pivot.groupby(level='one', as_index=False).apply(lambda x: x.sample(n=1))
Out[13]:
four three
one two
0 A 6.0 6.0 6.0
1 B 4.0 4.0 4.0
2 C 2.0 2.0 2.0注意:这每次都会选择一个随机行。
作为另一种选择,一种可能更具表现力的变体(提取子帧):
In [21]: df.iloc[[np.random.choice(x) for x in g.indices.values()]]
Out[21]:
four one three two
1 5.0 B 5.0 5.0
3 3.0 C 3.0 3.0
0 6.0 A 6.0 6.0https://stackoverflow.com/questions/37427919
复制相似问题