【问题标题】:Sampling from a large dataset从大型数据集中采样
【发布时间】:2021-08-08 21:14:48
【问题描述】:

我有一个包含 112k 行和 2 列的数据集。如何从这个数据集中平均采样以获得一个大约 10k 行的小数据集?

我的意思是相等,因为这个数据集有 56k 行,列名为 True=1,56k 行,列名为 ``´True=0```。

所以我想用True=1 列采样 10k 行和 5k 列,用True=0 采样 5k。

谢谢

【问题讨论】:

  • 你能分享一个小样本吗,你试过用熊猫sample吗?

标签: python pandas


【解决方案1】:

这被称为具有相等分配的分层随机样本(即每组的样本大小相同)在这种情况下也发生比例分配(每组的样本成比例到组的大小)。

可以使用groupby.sample实现:

df.groupby("my_column").sample(n=5000)

关于这个主题有一个fewearlierquestions,但它们涉及稍微复杂一些的情况,并且似乎在pandas v1.1中引入groupby.sample方法之前已经得到了回答。

【讨论】:

    【解决方案2】:

    For dataset split StratifiedKFold would help

    This cross-validation object is a variation of KFold that returns stratified folds. The folds are made by preserving the percentage of samples for each class.
    

    用法

    >>> from sklearn.model_selection import StratifiedKFold
    >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
    >>> y = np.array([0, 0, 1, 1])
    >>> skf = StratifiedKFold(n_splits=2)
    >>> skf.get_n_splits(X, y)
    2
    >>> print(skf)  
    StratifiedKFold(n_splits=2, random_state=None, shuffle=False)
    >>> for train_index, test_index in skf.split(X, y):
    ...    print("TRAIN:", train_index, "TEST:", test_index)
    ...    X_train, X_test = X[train_index], X[test_index]
    ...    y_train, y_test = y[train_index], y[test_index]
    TRAIN: [1 3] TEST: [0 2]
    TRAIN: [0 2] TEST: [1 3]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-18
      • 2019-05-25
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 2017-04-05
      • 2019-10-02
      • 2017-02-02
      相关资源
      最近更新 更多