Advertisement
vmamontov

join_data

Dec 23rd, 2021 (edited)
923
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. # Description:
  2. # join data from other dataframe
  3. # used methods '.assign' and '.explode' (for melt),
  4. # and '.merge' (for join)
  5.  
  6. import pandas as pd
  7.  
  8. df1 = pd.DataFrame([[0, 'text1', 'value1, value2'],
  9.                     [1, 'text2', 'value3, value4'],
  10.                     [2, 'text3', 'value5, value6']])
  11. df1.columns = ['cnt', 'text', 'values']
  12. # print(df1)
  13.  
  14. df2 = pd.DataFrame([[0, 'value1', 'Moscow'],
  15.                     [1, 'value2', 'Tokyo'],
  16.                     [2, 'value3', 'London'],
  17.                     [3, 'value4', 'Berlin'],
  18.                     [4, 'value5', 'Las Vegas'],
  19.                     [5, 'value6', 'Rio de Janeiro']])
  20. df2.columns = ['indx', 'code_value', 'data']
  21. # print(df2)
  22.  
  23. df1 = df1.assign(code_value=df1['values'].str.split(', '))
  24. df1 = df1.explode('code_value')
  25. df1 = pd.merge(df1, df2, how='left', on='code_value')
  26. df1 = df1.drop('indx', axis=1)
  27. df1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement