Skip to main content
 首页 » 编程设计

python之比率为 1 :1 of specific column entry 的 Pandas 随机样本

2025年05月04日8JustinYoung

我有一个 pandas dataframe 对象,其列 ['text', 'label'] 的标签值为 'pos' 或 'neg'。

问题是我有更多带有“neg”标签的列,就像我有“pos”标签一样。

现在的问题是,是否可以随机选择与“pos”句子一样多的“neg”句子,这样我就能得到一个新的数据框,两个标签的比例为 50:50?

我是否必须计算“pos”句子并将它们全部放入一个新的数据框中,然后执行 neg_df = dataframe.sample(n=pos_count) 并将其附加到之前创建的所有正数据框中,还是有更快的方法?

感谢您的帮助。

请您参考如下方法:

# Sample data. 
df = pd.DataFrame({'text': ['a', 'b', 'c', 'd', 'e'],  
                   'label': ['pos'] * 2 + ['neg'] * 3}) 
>>> df 
  label text 
0   pos    a 
1   pos    b 
2   neg    c 
3   neg    d 
4   neg    e 
 
# Create views of 'pos' and 'neg' text. 
neg_text = df.loc[df.label == 'neg', 'text'] 
pos_text = df.loc[df.label == 'pos', 'text'] 
 
# Equally sample 'pos' and 'neg' with replacement and concatenate into a dataframe. 
result = pd.concat([neg_text.sample(n=5, replace=True).reset_index(drop=True),  
                    pos_text.sample(n=5, replace=True).reset_index(drop=True)], axis=1) 
 
result.columns = ['neg', 'pos'] 
 
>>> result 
  neg pos 
0   c   b 
1   d   a 
2   c   b 
3   d   a 
4   e   a