Pandas数据帧中的随机行选择

Joh*_*ohn 140 python pandas

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

在R中,使用汽车包,有一个some(x, n)类似于头部的有用功能,但在这个例子中,从x中随机选择10行.

我也查看了切片文档,似乎没有任何等价物.

更新

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

df.sample(n)

rya*_*lon 231

使用pandas版本0.16.1及以上版本,现在有一个DataFrame.sample 内置方法:

import pandas

df = pandas.DataFrame(pandas.np.random.random(100))

# Randomly sample 70% of your dataframe
df_percent = df.sample(frac=0.7)

# Randomly sample 7 elements from your dataframe
df_elements = df.sample(n=7)
Run Code Online (Sandbox Code Playgroud)

对于上述任一方法,您可以通过执行以下操作来获取其余行:

df_rest = df.loc[~df.index.isin(df_percent.index)]
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案。另外,为了确保代码的可重复性,您可能需要将“random_state”添加到“sample”中。例如,`df_percent = df.sample(frac=0.7, random_state=42)` (2认同)

eum*_*iro 52

像这样的东西?

import random

def some(x, n):
    return x.ix[random.sample(x.index, n)]
Run Code Online (Sandbox Code Playgroud)

  • 谢谢@eumiro.我还发现`df.ix [np.random.random_integers(0,len(df),10)]`也可以. (7认同)
  • 如果你想使用numpy,那么你也可以做`df.ix [np.random.choice(df.index,10)]`. (7认同)
  • 有人在另一篇文章中提到过`np.random.choice`的速度是`random.sample`的两倍 (7认同)
  • 如果你使用np.random.choice你必须指定replace = False,否则你将获得重复的行! (5认同)
  • 我认为“.ix”已被弃用,您应该使用 .loc 进行基于标签的索引 (2认同)

jpp*_*jpp 13

sample

从v0.20.0开始,您可以使用pd.DataFrame.sample,它可用于返回固定数目的行或行百分比的随机样本:

df = df.sample(n=k)     # k rows
df = df.sample(frac=k)  # int(len(df.index) * k) rows
Run Code Online (Sandbox Code Playgroud)

为了重现性,您可以指定一个整数random_state,等效于使用np.ramdom.seed。因此,例如np.random.seed = 0,您无需设置,就可以:

df = df.sample(n=k, random_state=0)
Run Code Online (Sandbox Code Playgroud)


rlm*_*mlr 7

执行此操作的最佳方法是使用随机模块中的示例函数,

import numpy as np
import pandas as pd
from random import sample

# given data frame df

# create random index
rindex =  np.array(sample(xrange(len(df)), 10))

# get 10 random rows from df
dfr = df.ix[rindex]
Run Code Online (Sandbox Code Playgroud)


Moj*_*chi 5

下面的行将从数据帧 df 的现有总行数中随机选择 n 行,而不进行替换。

df = df.take(np.random.permutation(len(df))[:n])
Run Code Online (Sandbox Code Playgroud)