简体   繁体   中英

Pandas replace values of a column with comparison to another Dataframe

I want to replace in PF column value by a value in another Dataframe if exists In yellow no correspondance, so leave value as it is):

在此处输入图像描述

and Dataframe with old value comparison and new value:

在此处输入图像描述

I tried to do this but does not work unicite['CustomerID'] = np.where(unicite['CustomerId'] == Fidclients['CustomerId'],Fidclients['Newvalue'], unicite['CustomerID'])

If I'm understanding the question correctly, you want to replace the values in CustomerID in the table unicite with the values in the column Newvalue if they exist in the column CustomerID within the table Fidclients .

I believe you'll have to merge the tables to achieve this. For example,

unicite = pd.DataFrame({'CustomerID': ['a', 'b', 'c']})
print(unicite)

    CustomerID
0   a
1   b
2   c

Fidclients = pd.DataFrame({'CustomerID': ['c', 'f', 'g'], 'Newvalue': ['x', 'y', 'z']})
print(Fidclients)

  CustomerID Newvalue
0          c        x
1          f        y
2          g        z

merged = unicite.merge(Fidclients, on='CustomerID', how='left')
merged.loc[merged.Newvalue.notnull(), 'CustomerID'] = merged.Newvalue
merged.drop('Newvalue', axis=1)

    CustomerID
0   a
1   b
2   x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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