如何在Python中利用另一个DataFrame替换列表形式的列值
解决DataFrame中ID列表替换为对应名称的问题
实现思路
先把存储ID与名称映射关系的df2转换成字典(键为ID,值为对应名称),再遍历df1的genre_ids列,批量将列表中的ID替换为字典里的对应名称。
完整代码
import pandas as pd # 原始数据 df1 = pd.DataFrame({'title':['The Godfather','Fight Club','The Empire'], 'genre_ids':[[18, 80],[18],[12, 28, 878]]}) df2 = pd.DataFrame({'id':[18,80,12,28,878,99],'name':['Action','Adventure','Adventure','Animation','Comedy','Documentary']}) # 构建ID到名称的映射字典 genre_map = df2.set_index('id')['name'].to_dict() # 替换genre_ids中的ID为对应名称 df1['genre_ids'] = df1['genre_ids'].apply(lambda x: [genre_map[id] for id in x]) # 输出结果 print(df1)
运行结果
title genre_ids 0 The Godfather [Action, Adventure] 1 Fight Club [Action] 2 The Empire [Adventure, Animation, Comedy]
(注:你提供的目标结果中第一行genre_ids写的是[Action, Horror],但根据df2的映射关系,ID80对应的名称是Adventure,上述结果为实际映射后的正确输出)
内容的提问来源于stack exchange,提问作者Manish Patel
相关产品推荐
相关产品推荐

