Example 1: merge on index pandas
pd.merge(df1, df2, left_index=True, right_index=True)
Example 2: pd merge on multiple columns
new_df = pd.merge(A_df, B_df, how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])
Example 3: join on column pandas
# df1 as main df and use the feild from df2 and map it into df1
df1.merge(df2,on='columnName',how='left')
Example 4: Merge Sort python
def merge_sort(arr):
# The last array split
if len(arr) <= 1:
return arr
mid = len(arr)
# Perform merge_sort recursively on both halves
left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:])
# Merge each side together
return merge(left, right, arr.copy())
def merge(left, right, merged):
left_cursor, right_cursor = 0, 0
while left_cursor < len(left) and right_cursor < len(right):
# Sort each one and place into the result
if left[left_cursor] <= right[right_cursor]:
merged[left_cursor+right_cursor]=left[left_cursor]
left_cursor += 1
else:
merged[left_cursor + right_cursor] = right[right_cursor]
right_cursor += 1
for left_cursor in range(left_cursor, len(left)):
merged[left_cursor + right_cursor] = left[left_cursor]
for right_cursor in range(right_cursor, len(right)):
merged[left_cursor + right_cursor] = right[right_cursor]
return merged
Example 5: joins in pandas
pd.merge(product,customer,left_on='Product_name',right_on='Purchased_Product')
Example 6: pandas merge python
import pandas as pd
df1 = pd.DataFrame({'lkey': ['foo', 'bar', 'baz', 'foo'],
'value': [1, 2, 3, 5]})
df2 = pd.DataFrame({'rkey': ['foo', 'bar', 'baz', 'foo'],
'value': [5, 6, 7, 8]})
df1.merge(df2, left_on='lkey', right_on='rkey')