示例方法仅支持frac=
关键字参数。请参阅API文档 http://dask.readthedocs.io/en/latest/dataframe-api.html#dask.dataframe.DataFrame.sample
您收到的错误来自 Pandas,而不是 Dask。
In [1]: import pandas as pd
In [2]: df = pd.DataFrame({'x': [1]})
In [3]: df.sample(frac=2000, replace=False)
ValueError: Cannot take a larger sample than population when 'replace=False'
解决方案1
正如 Pandas 错误所示,考虑采样有更换
In [4]: df.sample(frac=2, replace=True)
Out[4]:
x
0 1
0 1
In [5]: import dask.dataframe as dd
In [6]: ddf = dd.from_pandas(df, npartitions=1)
In [7]: ddf.sample(frac=2, replace=True).compute()
Out[7]:
x
0 1
0 1
解决方案2
这可能会帮助某人..
我从某个地方发现了这个,但不记得在哪里了。
这将正确地显示结果,不会出现错误。 (这是针对 pandas 的,我不知道 dask)。
import pandas as pd
df = pd.DataFrame({'a': [1,2,3,4,5,6,7],
'b': [1,1,1,2,2,3,3]})
# this is fixed number, will be error when data in group is less than sample size
df.groupby('b').apply(pd.DataFrame.sample, n=1)
# this is flexible with min, no error, will return 3 or less than that
df.groupby(['b'], as_index=False, group_keys=False
).apply(
lambda x: x.sample(min(3, len(x)))
)