从 len 18000 的 Dask Dataframe 中采样 n= 2000 会产生错误 当“replace=False”时,无法获取比总体更大的样本

问题描述 投票:0回答:5

我有一个从 csv 文件创建的 dask 数据框,并且

len(daskdf)
返回 18000,但是当我
ddSample = daskdf.sample(2000)
时,我收到错误

ValueError: Cannot take a larger sample than population when 'replace=False'

如果数据框大于样本大小,我可以不放回抽样吗?

python dask
5个回答
17
投票

示例方法仅支持

frac=
关键字参数。 请参阅API文档

您收到的错误来自 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)))
        )

1
投票

我从某个地方找到这个,但不记得在哪里了。

这将正确地显示结果,没有错误。 (这是针对 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)))
        )

0
投票

sample
方法中,将参数
replace
更改为
True

df.sample(samples, replace=True)

表明DataFrame的大小大于其需要的样本数量。所以这是一个临时解决方法。


0
投票

也许重点是他想从原始数据框中提取行样本,所以恕我直言,我认为你应该指定

axis=0
从行中采样。


0
投票

我也遇到过同样的事情,我认为这是一个错误,因为你的人口规模是 18K,而你尝试采样 2K,它应该可以工作。

尝试自己做:

indices_to_keep = numpy.random.choice(daskdf.index, size=2000)
df_sampled = daskdf.loc[indices_to_keep]
© www.soinside.com 2019 - 2024. All rights reserved.