Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas matching data frame structure

I have two data frames like the ones below:

d = {'var1': [1, 2, 3, 4], 'var2': [5, 6, 7, 8], 'var3': [9, 10, 11, 12]}
df = pd.DataFrame(data=d)
df
    var1   var2  var3
0     1     5      9
1     2     6      10
2     3     7      11
3     4     8      12

and

d2 = {'var1': [4, 1, 3], 'var2': [5, 7, 7]}
df2 = pd.DataFrame(data=d2)
df2
    var1   var2
0     1     5
1     2     7
2     3     7

I want df2 to have the same columns and column order as the original df

so the results would look like:

df2
    var1   var2  var3
0     1     5     NaN
1     2     7     NaN
2     3     7     NaN

I know that I can manually assign a new column in this example called 'var3' and set its values to NaN, but I am looking for a general solution where this needs to be done on many data frames with many columns.

like image 550
Mustard Tiger Avatar asked Jul 20 '26 19:07

Mustard Tiger


2 Answers

Try using reindex:

df2.reindex(df.columns, axis=1)

Output:

   var1  var2  var3
0     4     5   NaN
1     1     7   NaN
2     3     7   NaN
like image 109
Scott Boston Avatar answered Jul 23 '26 08:07

Scott Boston


Using align

df2,_=df2.align(df,axis=1)
df2
Out[190]: 
   var1  var2  var3
0     4     5   NaN
1     1     7   NaN
2     3     7   NaN
like image 38
BENY Avatar answered Jul 23 '26 10:07

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!