Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we update column data in rows of similar columns with the data found after merge operation?

Tags:

I can find equal column data with concatenation function. But there is something else I want to do. For example; If the 'customer ID' in the second file has values ​​equal to the customer ID in the first file; I want to save the values ​​in the 'customer rating' column in the same row with equal values ​​in the 'customer rating' column in the row where the 'customer id' column is equal in the first file.

 pd.merge(first_file_data,second_file_data,left_on='CUSTOMER ID',right_on='CUSTOMER ID')

Output:

Similar customer IDs in the merge transaction:

FİRST FİLE

  CUSTOMER ID  CUSTOMER SCORE  
0  3091250      Nan
1  1122522      Nan

SECOND_FİLE

  CUSTOMER ID  CUSTOMER SCORE
0  3091250      750
1  1122522      890
like image 832
sanane sanane Avatar asked Oct 24 '20 14:10

sanane sanane


1 Answers

You can use df.fillna() function. Just set same indexes on df1 and df2:

out = df1.set_index('CUSTOMER_ID').fillna(df2.set_index('CUSTOMER_ID')).reset_index()

print(out)

Prints:

   CUSTOMER_ID  CUSTOMER_SCORE
0      3091250           750.0
1      1122522           890.0

EDIT: To replace NaNs only in one row in df1:

df1['CUSTOMER_SCORE'] = df1.set_index('CUSTOMER_ID')['CUSTOMER_SCORE'].fillna(df2.set_index('CUSTOMER_ID')['CUSTOMER_SCORE']).values
print(df1)

Prints:

   CUSTOMER_ID  CUSTOMER_SCORE
0      3091250           750.0
1      1122522           890.0
like image 185
Andrej Kesely Avatar answered Sep 29 '22 11:09

Andrej Kesely