I am not sure if it is the right expression, but searching merge or change index didn't get me anywhere. Basically I have two dataframes:
df_A = pd.DataFrame(1, index=[1,2,3], columns = [1,2,3])
df_B = pd.DataFrame(0, index=[1,2,4], columns = [1,2,5])
I want to transform df_A and df_B such that both share the same index and columns, which are the unions of the two. The missing values will be filled with NaN:
df_A_new:
1 2 3 5
index
1 1 1 1 NaN
2 1 1 1 NaN
3 1 1 1 NaN
4 NaN NaN NaN NaN
df_B_new:
1 2 3 5
index
1 0 0 NaN 0
2 0 0 NaN 0
3 NaN NaN NaN NaN
4 0 0 NaN 0
You can use .union
and .reindex
.
rows = df_A.index.union(df_B.index)
cols = df_A.columns.union(df_B.columns)
df_A_new = df_A.reindex(index=rows, columns=cols)
df_B_new = df_B.reindex(index=rows, columns=cols)
df_A_new
looks like
1 2 3 5
1 1.0 1.0 1.0 NaN
2 1.0 1.0 1.0 NaN
3 1.0 1.0 1.0 NaN
4 NaN NaN NaN NaN
df_B_new
looks like:
1 2 3 5
1 0.0 0.0 NaN 0.0
2 0.0 0.0 NaN 0.0
3 NaN NaN NaN NaN
4 0.0 0.0 NaN 0.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With