I'm trying to merge/concatenate two columns where both have related, but separate text data delimited by "|" in addition to replacing certain names with "" and replace the | with '\n'.
For example, the original data may be:
First Names Last Names
0 Jim|James|Tim Simth|Jacobs|Turner
1 Mickey|Mini Mouse|Mouse
2 Mike|Billy|Natasha Mills|McGill|Tsaka
If I want to merge/concatenate to derive Full Names and remove entries tied to "Smith" the final df should look like:
First Names Last Names Full Names
0 Jim|James|Tim Simth|Jacobs|Turner James Jacobs\nTim Turner
1 Mickey|Mini Mouse|Mouse Mickey Mouse\nMini Mouse
2 Mike|Billy|Natasha Mills|McGill|Tsaka Mike Mills\nBilly McGill\nNatasha Tsaka
My current approach so far has been:
def parse_merge(df, col1, col2, splitter, new_col, list_to_exclude):
orig_order = pd.Series(list(df.index)).rename('index')
col1_df = pd.concat([orig_order, df[col1], df[col1].str.split(splitter, expand=True)], axis = 1)
col2_df = pd.concat([orig_order, df[col2], df[col2].str.split(splitter, expand=True)], axis = 1)
col1_melt = pd.melt(col1_df, id_vars=['index', col1], var_name='count')
col2_melt = pd.melt(col2_df, id_vars=['index', col2], var_name='count')
col2_melt['value'] = '(' + col2_melt['value'].astype(str) + ')'
col2_melt = col2_melt.rename(columns={'value':'value2'})
melted_merge = pd.concat([col1_melt, col2_melt['value2']], axis = 1 )
if len(list_to_exclude) > 0:
list_map = map(re.escape, list_to_exclude)
melted_merge.ix[melted_merge['value2'].str.contains('|'.join(list_map)), ['value', 'value2']] = ''
melted_merge[new_col] = melted_merge['value'] + " " + melted_merge['value2']
if I call:
parse_merge(names, 'First Names', 'Last Names', 'Full Names', ['Smith'])
The data becomes:
Index First Names count value value2 Full Names
0 0 Jim|James|Tim 0 Jim Smith ''
1 1 Mickey|Mini 0 Mickey Mouse Mickey Mouse
2 2 Mike|Billy|Natasha 0 Mike Mills Mike Mills
Just not sure how to finish this out without any loops or if there is a more efficient / totally different approach.
Thanks for all the input!