[英]Sample pandas dataframe by column value
我有一個 pandas dataframe,名為ratings_full
,形式為:
userID nr_votes
123 12
124 14
234 22
346 35
763 45
238 1
127 17
我想對這個 dataframe 進行采樣,因為它包含數以萬計的用戶。 我想提取 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)
然后我必須將數據框重新組合在一起。 這不是一個理想的答案,但它可能會奏效。 我什至會先嘗試存儲桶並將存儲桶列用作我的“標簽”。
我們可以通過做索引切片來做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()
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.