有没有办法从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)
eum*_*iro 52
像这样的东西?
import random
def some(x, n):
return x.ix[random.sample(x.index, n)]
Run Code Online (Sandbox Code Playgroud)
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)
执行此操作的最佳方法是使用随机模块中的示例函数,
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)
下面的行将从数据帧 df 的现有总行数中随机选择 n 行,而不进行替换。
df = df.take(np.random.permutation(len(df))[:n])
Run Code Online (Sandbox Code Playgroud)