Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Description:
- # join data from other dataframe
- # used methods '.assign' and '.explode' (for melt),
- # and '.merge' (for join)
- import pandas as pd
- df1 = pd.DataFrame([[0, 'text1', 'value1, value2'],
- [1, 'text2', 'value3, value4'],
- [2, 'text3', 'value5, value6']])
- df1.columns = ['cnt', 'text', 'values']
- # print(df1)
- df2 = pd.DataFrame([[0, 'value1', 'Moscow'],
- [1, 'value2', 'Tokyo'],
- [2, 'value3', 'London'],
- [3, 'value4', 'Berlin'],
- [4, 'value5', 'Las Vegas'],
- [5, 'value6', 'Rio de Janeiro']])
- df2.columns = ['indx', 'code_value', 'data']
- # print(df2)
- df1 = df1.assign(code_value=df1['values'].str.split(', '))
- df1 = df1.explode('code_value')
- df1 = pd.merge(df1, df2, how='left', on='code_value')
- df1 = df1.drop('indx', axis=1)
- df1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement