gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:36:45 24 4
gpt4 key购买 nike

我有一个 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

关于python - 比率为 1 :1 of specific column entry 的 Pandas 随机样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35346421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com