我有包含列类的数据框架,在类列中有3个文本值‘正’、‘负’和‘中性’。我想将40%的中性变为正,30%的中性变为负值,并在使用熊猫python的数据帧中保留其余30%的中性。
发布于 2022-02-22 10:15:12
树立一个榜样:
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然后我们就可以得到中性的指数,然后对它们进行洗牌,然后拆分:
# 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'价值计数(分数):
>>> df.value_counts(normalize=True)
positive 0.468
negative 0.433
neutral 0.099https://stackoverflow.com/questions/71219166
复制相似问题