如何用DataFrame2的值修正DataFrame1对应Product_ID的count与weight?
用DataFrame2修正DataFrame1的指定字段(保留date)
需求:使用DataFrame2中的count和weight值,替换DataFrame1中相同Product_ID对应的这两个字段,同时保留date字段不变。
原始数据
DataFrame1
Product_ID count weight date 0 pid_1 2 10 1/01/2023 1 pid_1 3 20 1/02/2023 2 pid_2 4 30 1/01/2023 3 pid_2 2 40 1/02/2023 4 pid_3 3 50 1/01/2023 5 pid_4 6 100 1/01/2023
DataFrame2
Product_ID count weight 0 pid_1 2 10 1 pid_2 3 20 2 pid_3 4 30
期望输出
Product_ID count weight date 0 pid_1 2 10 1/01/2023 1 pid_1 2 10 1/02/2023 2 pid_2 3 20 1/01/2023 3 pid_2 3 20 1/02/2023 4 pid_3 4 30 1/01/2023 5 pid_4 6 100 1/01/2023
解决方案
推荐使用向量化操作(比循环更高效,适合大数据量):
import pandas as pd # 初始化两个DataFrame df1 = pd.DataFrame({ 'Product_ID': ['pid_1', 'pid_1', 'pid_2', 'pid_2', 'pid_3', 'pid_4'], 'count': [2, 3, 4, 2, 3, 6], 'weight': [10, 20, 30, 40, 50, 100], 'date': ['1/01/2023', '1/02/2023', '1/01/2023', '1/02/2023', '1/01/2023', '1/01/2023'] }) df2 = pd.DataFrame({ 'Product_ID': ['pid_1', 'pid_2', 'pid_3'], 'count': [2, 3, 4], 'weight': [10, 20, 30] }) # 将df2以Product_ID为索引,方便映射 df2_indexed = df2.set_index('Product_ID') # 替换count字段:匹配到则用df2的值,否则保留原值 df1['count'] = df1['Product_ID'].map(df2_indexed['count']).fillna(df1['count']).astype(int) # 替换weight字段:逻辑同上 df1['weight'] = df1['Product_ID'].map(df2_indexed['weight']).fillna(df1['weight']).astype(int) # 查看结果 print(df1)
代码说明
df2.set_index('Product_ID'):把df2的索引设为Product_ID,后续可通过Product_ID快速查找对应的count和weight值。map(df2_indexed['count']):根据df1的Product_ID,从df2_indexed中取出对应的count值,未匹配到的会返回NaN。fillna(df1['count']):把NaN替换为df1原来的count值,保证未在df2中出现的Product_ID(如pid_4)保留原始数据。astype(int):由于fillna后数据类型可能变为float,转成int保持数值类型一致。
内容的提问来源于stack exchange,提问作者Pra
相关产品推荐
相关产品推荐

