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

如何基于条件用字典值替换Pandas DataFrame列的指定值

解决Pandas中仅替换指定条件列值的问题

问题背景

现有如下DataFrame:

import pandas as pd

movies = {'name': ['Movie A', 'Movie B', 'Movie C', 'Movie D', 'Movie E'], 
          'genre' : ['Action', 'Crime', 'Drama', 'Comedy', 'Animation'], 
          'runtime' : [0, 100, 0, 120,0]}

df = pd.DataFrame(movies)

同时有存储各类型电影中位时长的字典:

genre_dict = {'Action': 107.0, 'Adventure': 108.0, 'Animation': 86.0, 'Comedy': 99.0, 'Crime': 111.0, 'Drama': 111.0, 'Family': 92.0, 'Fantasy': 103.0, 'History': 124.0, 'Horror': 94.5, 'Music': 105.0, 'Mystery': 100.5, 'Romance': 104.0, 'Science Fiction': 106.0, 'TV Movie': 92.0, 'Thriller': 102.0, 'War': 118.0, 'Western': 119.0}

需求:仅将runtime列中值为0的条目替换为对应genre的中位时长,保留非0值不变。

之前尝试的map方法会替换所有runtime值,不符合需求:

df['runtime'] = df['genre'].map(genre_dict)

解决方案

方法1:使用loc条件索引

通过loc精准定位需要替换的行,仅对runtime == 0的单元格赋值:

df.loc[df['runtime'] == 0, 'runtime'] = df.loc[df['runtime'] == 0, 'genre'].map(genre_dict)

方法2:使用where方法

where保留满足条件的原数值,替换不满足条件的值:

df['runtime'] = df['runtime'].where(df['runtime'] != 0, df['genre'].map(genre_dict))

方法3:使用mask方法

mask替换满足条件的值,保留其余原数值(与where逻辑相反):

df['runtime'] = df['runtime'].mask(df['runtime'] == 0, df['genre'].map(genre_dict))

验证结果

运行任意一种方法后,得到目标DataFrame:

print(df)
# 输出:
#       name      genre  runtime
# 0  Movie A     Action    107.0
# 1  Movie B      Crime    100.0
# 2  Movie C      Drama    111.0
# 3  Movie D     Comedy    120.0
# 4  Movie E  Animation     86.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:15:33