按列值采样熊猫数据框

时间:2020-05-26 13:42:34

标签: python python-3.x pandas sampling

我有一个名为ratings_full的熊猫数据框,格式为:

userID   nr_votes
123      12
124      14
234      22
346      35
763      45
238      1
127      17

我想对该数据框进行采样,因为它包含成千上万的用户。我想提取100个用户,但是要以某种方式对具有较低值nr_votes的用户进行优先级排序,而不是仅对它们进行采样。因此,nr_votes上有一种“分层抽样”。可能吗?

这是我到目前为止所管理的:

SAMPLING_FRACTION = 0.0007

uid_samples = ratings_top['userId'] \
                        .drop_duplicates() \
                        .sample(frac=SAMPLING_FRACTION, 
                                replace=False, 
                                random_state=1)
ratings_sample = pd.merge(ratings_full, uid_samples, on='userId', how='inner')

这仅提供跨userID的随机抽样,但不能确保抽样以某种方式分层。

编辑:如果我们可以将nr_votes分成N个存储桶,然后对存储桶进行分层采样,我什至会很高兴。

编辑2 我现在正在尝试这个:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X=ratings_full.drop([nr_votes], axis=1),
             y=ratings_full.nr_votes, 
             test_size=0.33, 
             random_state=42, 
             stratify=y)

然后我必须将数据帧放回原处。这不是理想的答案,但可能会起作用。我什至会尝试首先进行存储,并将存储桶列用作我的“标签”。

2 个答案:

答案 0 :(得分:1)

我们可以通过做索引切片来完成np.random.choice

n = len(ratings_top)
idx = np.random.choice(ratings_top.index.values, p=ratings_top['probability'], size=n*0.0007, replace=True)

然后

sample_df = df.loc[idx].copy()

答案 1 :(得分:0)

from sklearn.model_selection import StratifiedShuffleSplit

n_splits = 1 
sss = model_selection.StratifiedShuffleSplit(n_splits=n_splits, 
                                                 test_size=0.1,
                                                 random_state=42)
train_idx, test_idx = list(sss.split(X, y))[0]