You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改DataFrame中特定标签对应的Sentiment_Score列值?

问题描述

我有如下DataFrame:

Sentiment_LabelSentiment_Score
Satisfied0.882621
Disappointed0.826413
Satisfied0.893627
Satisfied0.863469
Disappointed0.982447

希望将所有标签为Disappointed的Sentiment_Score值用1减去,得到如下目标输出:

Sentiment_LabelSentiment_Score
Satisfied0.882621
Disappointed0.173587
Satisfied0.893627
Satisfied0.863469
Disappointed0.017553

我曾尝试用groupby()拆分数据到不同列,但产生的NaN值导致后续计算困难,且希望保留原有列结构。对应的DataFrame初始化代码如下:

import pandas as pd

df = pd.DataFrame({
    'Sentiment_Label': ["Satisfied", "Disappointed", "Satisfied", "Satisfied", "Disappointed"],
    'Sentiment_Score': [0.882621, 0.826413, 0.893627, 0.863469, 0.982447],
})
解决方案

不需要使用groupby(),直接通过条件筛选修改指定行的值即可,以下是几种简洁的实现方式:

方法1:使用loc直接定位修改

通过布尔索引筛选出Sentiment_Label为Disappointed的行,直接计算赋值:

df.loc[df['Sentiment_Label'] == 'Disappointed', 'Sentiment_Score'] = 1 - df.loc[df['Sentiment_Label'] == 'Disappointed', 'Sentiment_Score']

方法2:使用where方法

where会保留满足条件的值,对不满足条件的行替换为指定表达式结果:

df['Sentiment_Score'] = df['Sentiment_Score'].where(df['Sentiment_Label'] != 'Disappointed', 1 - df['Sentiment_Score'])

方法3:使用mask方法

mask和where逻辑相反,对满足条件的行替换为指定表达式结果:

df['Sentiment_Score'] = df['Sentiment_Score'].mask(df['Sentiment_Label'] == 'Disappointed', 1 - df['Sentiment_Score'])

以上三种方法都能在保留原有DataFrame结构的前提下完成需求,不会产生NaN值。

内容的提问来源于stack exchange,提问作者Faraz Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 17:02:41