如何修改DataFrame中特定标签对应的Sentiment_Score列值?
问题描述
我有如下DataFrame:
| Sentiment_Label | Sentiment_Score |
|---|---|
| Satisfied | 0.882621 |
| Disappointed | 0.826413 |
| Satisfied | 0.893627 |
| Satisfied | 0.863469 |
| Disappointed | 0.982447 |
希望将所有标签为Disappointed的Sentiment_Score值用1减去,得到如下目标输出:
| Sentiment_Label | Sentiment_Score |
|---|---|
| Satisfied | 0.882621 |
| Disappointed | 0.173587 |
| Satisfied | 0.893627 |
| Satisfied | 0.863469 |
| Disappointed | 0.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
相关产品推荐
相关产品推荐

