pandas 数据框中的随机行选择 [英] Random row selection in Pandas dataframe

查看:41
本文介绍了 pandas 数据框中的随机行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从Pandas的DataFrame中选择随机行.

Is there a way to select random rows from a DataFrame in Pandas.

在R中,使用汽车包装,有一个有用的函数some(x, n),它与head类似,但在此示例中,它从x中随机选择10行.

In R, using the car package, there is a useful function some(x, n) which is similar to head but selects, in this example, 10 rows at random from x.

我也看过切片文档,似乎没有什么等效的.

I have also looked at the slicing documentation and there seems to be nothing equivalent.

现在使用版本20.有一个示例方法.

Now using version 20. There is a sample method.

df.sample(n)

推荐答案

像这样吗?

import random

def some(x, n):
    return x.ix[random.sample(x.index, n)]

注意:自Pandas v0.20.0起,ix

Note: As of Pandas v0.20.0, ix has been deprecated in favour of loc for label based indexing.

这篇关于 pandas 数据框中的随机行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆