alphanumeric alphanumeric - 1 year ago 61
Python Question

How to assign default value while performing concat on DataFrames


dataframe gets NaN value assigned to the column
which is not presented in dataframe

dfa = pd.DataFrame({'a':[1]})
dfb = pd.DataFrame({'a':[10], 'b':[10]})
result = pd.concat([dfa, dfb])
print result

Here is the result:

a b
0 1 NaN
0 10 10.0

Instead of
I would rather assign an integer value
. Could it be done?

Answer Source

You can use reindex dfa by columns of dfb and add parameter fill_value=0:

dfa = dfa.reindex(columns=dfb.columns, fill_value=0)
print (dfa)
   a  b
0  1  0

result = pd.concat([dfa, dfb], ignore_index=True)
print (result) 
    a   b
0   1   0
1  10  10
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download