Given two dataframes with different columns, some overlapping.Combine on the index to…
- User
Given two dataframes with different columns, some overlapping.Combine on the index to get a single dataframe, preferring values from the left dataframe if they are not null and filling values from the right if the left are null
Assistant
To combine two dataframes with different columns, some overlapping, and preferring values from the left dataframe if they are not null, and filling values from the right if the left are null, you can use the combine_first() method in pandas. Here's an example: pythonimport pandas as pd
Create two dataframes
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, None, 6], 'C': [7, 8, 9]}, index=['a', 'b', 'c']) df2 = pd.DataFrame({'A': [10, 11, 12], 'B': [13, 14, 15], 'D': [16, 17, 18]}, index=['a', 'b', 'c'])
Combine dataframes
combined_df = df1.combine_first(df2)
print(combined_df) Output: A B C D a 1.0 4.0 7.0 16.0 b 2.0 14.0 8.0 17.0 c 3.0 6.0 9.0 18.0 In this example:
df1 and df2 have different columns, with 'A' and 'B' as overlapping columns. combined_df is the result of combining df1 and df2 using combine_first(). The values from the 'A' and 'B' columns of df1 are preferred if they are not null. If the values in df1 are null, the corresponding values from df2 are used. The columns that are not present in df1 ('D') are filled with the values from df2.