首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将单个组的某个部分的值随机更改为其他组的值。

将单个组的某个部分的值随机更改为其他组的值。
EN

Stack Overflow用户
提问于 2022-02-22 09:55:33
回答 1查看 69关注 0票数 1

我有包含列类的数据框架,在类列中有3个文本值‘正’、‘负’和‘中性’。我想将40%的中性变为正,30%的中性变为负值,并在使用熊猫python的数据帧中保留其余30%的中性。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-22 10:15:12

树立一个榜样:

代码语言:javascript
复制
np.random.seed(0)
df = pd.DataFrame({'col': np.random.choice(['positive', 'negative', 'neutral'], 1000)})

#         col
# 0  positive
# 1  negative
# 2  positive
# 3  negative
# 4  negative

df.value_counts(normalize=True)
# positive    0.337
# negative    0.335
# neutral     0.328

然后我们就可以得到中性的指数,然后对它们进行洗牌,然后拆分:

代码语言:javascript
复制
# get shuffled index of neutral
idx = df[df['col'].eq('neutral')].sample(frac=1).index
L = len(idx)

# replace first random 40%
df.loc[idx[:int(L*0.4)], 'col'] = 'positive'
# replace next random 30%
df.loc[idx[int(L*0.4):int(L*0.7)], 'col'] = 'negative'

价值计数(分数):

代码语言:javascript
复制
>>> df.value_counts(normalize=True)
positive    0.468
negative    0.433
neutral     0.099
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71219166

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档