如何在Pandas中从DataFrame中随机选择行?
在R中,使用car包,有一个有用的函数some(x, n)
,类似于head但从x中随机选择10行。
我也查看了切片文档,但似乎没有相应的功能。
更新
现在使用版本20。有一个sample方法。
df.sample(n)
从 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)
对于上述任一种方法,您可以通过执行以下操作获取其余行:
df_rest = df.loc[~df.index.isin(df_percent.index)]
根据 Pedram
的评论,如果您想要获得可重现的样本,请传递 random_state
参数。
df_percent = df.sample(frac=0.7, random_state=42)
df_0.7
不是一个有效的名称。此外,我建议用 df_rest = df.loc[df.index.difference(df_0_7.index)]
替换 df_rest = df.loc[~df.index.isin(df_0_7.index)]
。 - Pietro Battistondifference()
有性能上的提升吗? - ryanjdillonsample
中添加random_state
。例如,df_percent = df.sample(frac=0.7, random_state=42)
。 - Pedram像这样的吗?
import random
def some(x, n):
return x.ix[random.sample(x.index, n)]
注意: 自从Pandas v0.20.0版本以后,ix
已经被弃用,取而代之的是基于标签的索引loc
。
df.ix[np.random.random_integers(0, len(df), 10)]
这个方法也可以达到同样的效果。 - Johndf.ix[np.random.choice(df.index, 10)]
。 - naught101np.random.choice
比random.sample
快两倍。 - Phanisample
从 v0.20.0 开始,您可以使用pd.DataFrame.sample
方法,它可用于返回固定行数或百分比的随机样本:
df = df.sample(n=k) # k rows
df = df.sample(frac=k) # int(len(df.index) * k) rows
为了重现实验结果,您可以指定一个整数random_state
,相当于使用np.random.seed
。所以,不是设置例如np.random.seed = 0
,您可以:df = df.sample(n=k, random_state=0)
最好的方法是使用随机模块中的样本函数。
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]
以下代码将从数据框df中不重复地随机选择n行数据,数量为总行数。
df = df.take(np.random.permutation(len(df))[:n])
np.random.random_integers(0, len(df), N)
,其中N
是一个大数。
df.sample(N, replace=True)
。详见这里。 - cs95