gpt-4.1-mini-2025-04-14· openai
from WildChat-4.8M
Let dataframe df1 has 5 columns, and df2 has 3 out of 5 columns. BUt create df2 with…
Private research annotation
Sign in to add a private research label or note.
- User
Let dataframe df1 has 5 columns, and df2 has 3 out of 5 columns. BUt create df2 with columns of df1 keep Nan for missing value
- Assistant
If you have two DataFrames,
df1anddf2, anddf2contains only 3 out of the 5 columns ofdf1, but you want to makedf2have all 5 columns ofdf1withNaNfor the missing columns, you can do it like this:Example:
pythonimport pandas as pd import numpy as np # Example df1 with 5 columns df1 = pd.DataFrame({ 'A': [1, 2], 'B': [3, 4], 'C': [5, 6], 'D': [7, 8], 'E': [9, 10] }) # df2 with only 3 columns from df1 df2 = pd.DataFrame({ 'A': [1, 3], 'C': [5, 7], 'E': [9, 11] }) # Make df2 have all columns of df1, with NaN for missing columns for col in df1.columns: if col not in df2.columns: df2[col] = np.nan # Reorder columns to match df1's column order df2 = df2[df1.columns] print(df2)