Pandas 基于两个标准的样本

Pandas Sample Based on Two Criteria

我有一个如下所示的数据框:

     feature     target
0       2        0
1       0        0
2       0        0
3       0        0
4       1        0
...    ...      ...
33208   1        0
33209   0        0
33210   2        0
33211   2        0
33212   1        0

feature列中有3个classes (0, 1, 2),在target列中有两个classes (0, 1).如果我按这两列对数据框进行分组,我会得到:

df.groupby(['feature', 'target']).size()

feature  target
0         0             4282
          1               81
1         0             8537
          1               37
2         0            20161
          1              115
dtype: int64

每个 feature class 都有 0s1s 作为 target 值,我需要找到一种对这些值进行采样的方法,我的意图是最后有这样的东西:

new_df.groupby(['feature', 'target']).size()

feature  target
0         0             4282
          1               81
1         0             4282
          1               37
2         0             4282
          1              115
dtype: int64

我需要对每个 feature class 的 target 个值进行采样,有什么建议吗?

根据 feature 的值,您有不同的分布。 您需要从分布中抽取 n 个值,前提是 feature 的值:假设有 2 种可能的结果,这是一个二项式分布问题。
下面显示的方法应该有助于 target 不一定是 (0, 1) 的情况 - 可以是任何东西(win vs loseA 队 vs B 队,依此类推)据我所知:

import numpy as np
import pandas as pd

# this is just reproducting your grouped end stated
df = pd.DataFrame({"feature":[0, 0, 1, 1, 2, 2], "target":[0, 1, 0, 1, 0, 1], "number":[4282, 81, 4282, 37, 4282, 115]})
df = df.set_index(["feature", "target"])

def sample_values(feature, sample_size):
    # select one of the distribution by feature
    df_sub = df.loc[feature]

    (event1, number1), (event2, number2) = zip(df_sub.index,df_sub["number"].tolist())

    return [event2 if np.random.binomial(1, number2/(number1+number2))==1 else event1 for _ in range(sample_size)]

print(sample_values(2, 100))

输出

[1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]