import pandas as pd # create two data frames with the same index df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c']) df2 = pd.DataFrame({'A': [7, 8, 9], 'B': [10, 11, 12]}, index=['b', 'c', 'd']) # perform index union on data frames new_index = df1.index.union(df2.index) # reindex data frames with new index df1 = df1.reindex(new_index) df2 = df2.reindex(new_index) # concatenate data frames into one result = pd.concat([df1, df2], axis=1) print(result)
A B A B a 1.0 4.0 NaN NaN b 2.0 5.0 7.0 10.0 c 3.0 6.0 8.0 11.0 d NaN NaN 9.0 12.0
import pandas as pd # create two data frames with different columns and index df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c']) df2 = pd.DataFrame({'C': [7, 8, 9], 'D': [10, 11, 12]}, index=['b', 'c', 'd']) # perform index union on data frames new_index = df1.index.union(df2.index) # reindex data frames with new index df1 = df1.reindex(new_index) df2 = df2.reindex(new_index) # concatenate data frames into one result = pd.concat([df1, df2], axis=1) print(result)
A B C D a 1.0 4.0 NaN NaN b 2.0 5.0 7.0 10.0 c 3.0 6.0 8.0 11.0 d NaN NaN 9.0 12.0In this example, we create two data frames with different columns and index. We perform index union using `pd.Index.union()` and reindex the data frames with the new index. Finally, we concatenate them into one data frame using `pd.concat()`. Overall, the pandas package library is used to perform the index union operation. The `pd.Index.union()` method allows for combining multiple data frames with the same columns and rows into one data frame with a new index.