Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Imports
- import functools as ft
- import pandas as pd
- df1 = pd.DataFrame({'X': {0: 'a', 1: 'b', 2: 'z'},
- 'B': {0: 0, 1: 4, 2: 3},
- 'C': {0: 2, 1: 9, 2: 0}
- })
- df2 = pd.DataFrame({'X': {0: 'a', 1: 'b', 2: 'z'},
- 'B': {0: 0, 1: 8, 2: 6},
- 'C': {0: 4, 1: 18, 2: 0}
- })
- df3 = pd.DataFrame({'X': {0: 'a', 1: 'b', 2: 'z'},
- 'B': {0: 12, 1: 0, 2: 4},
- 'C': {0: 3, 1: 9, 2: 2}
- })
- dfs = [df1,df2,df3]
- # Merge the DataFrames
- merged = ft.reduce(lambda left,right: pd.merge(left,right,on='X'), dfs).set_index('X')
- first_index = []
- second_index = []
- for i in range(len(dfs)):
- f_val = "{}{}".format("F", i+1)
- first_index.extend((f_val, f_val))
- second_index.extend(("B", "C"))
- # Create a MultiIndex
- arrays = [first_index, second_index]
- columns = pd.MultiIndex.from_arrays(arrays)
- # Create your DataFrame
- df = pd.DataFrame(data=merged.as_matrix(),
- columns=columns,
- index = dfs[0]['X'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement