简体   繁体   English

比较两个熊猫数据框并根据结果更新一个

[英]Compare two pandas dataframes and update one, depending on results

I have the following (simplified) data; 我有以下(简化的)数据;

import pandas as pd

a = [['10', '12345', '4'], ['15', '78910', '3'], ['8', '23456', '10']]
b = [['10', '12345'], ['15', '78910'], ['9', '23456']]

df_a = pd.DataFrame(a, columns=['id', 'sku', 'quantity '])
df_b = pd.DataFrame(b, columns =['id','sku'])

I need to compare the 'id and 'sku' columns from both dataframes and for those that match I need to update df_a['quantity'] to equal '0'. 我需要比较两个数据帧中的“ id”和“ sku”列,对于匹配的那些,我需要将df_a['quantity']更新为等于“ 0”。

So, something like an if statement? 那么,类似if语句?

if (df_a['id'] == df_b['id']) and (df_a['sku'] == df_b['sku']):
    df_a['quantity']=0

这应该做

df_a.loc[(df_b['id'] == df_a['id']) & (df_a['sku'] == df_b['sku']), 'quantity '] = 0

Not the most elegant way, but will do the trick if dataframes have different shapes. 这不是最优雅的方法,但是如果数据帧具有不同的形状,则可以解决问题。

a_id_sku = df_a.id + df_a.sku
b_id_sku = df_b.id + df_b.sku

df_a.loc[a_id_sku.isin(b_id_sku), 'quantity '] = 0

Let me know if this worked 让我知道这是否有效

Another approach using pandas merge : 另一种使用熊猫合并的方法

df_a.loc[pd.merge(df_a, df_b, on = ['id', 'sku'] , how='left',
    indicator=True)['_merge'] == 'both', 'quantity'] = 0

df_a
    id  sku quantity
0   10  12345   0
1   15  78910   0
2   8   23456   10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM