Imran Ahmad Ghazali
Imran Ahmad Ghazali

Reputation: 625

How to take value of common column in one dataframe from another?

I have Empty data frame with some columns,

df_skeleton = pd.DataFrame(columns=columns)

And I have another dataframe df which is subset of above dataframe,But in this dataframe, I have a single row with values.

I want to put a corresponding value of the second dataframe into the

df_skeleton 

and all other columns values equal to zero

Eg:

df_skeleton is having 10 columns, name from col1,col2.....col10,

   col1   col2 col3 col4 col5 col5 co6 col7 col8 col9 col10
0

but it does not contain any row or values. It is just skeleton.

And my df is having 3 columns

      col1 col3 col7
 0    23    45   10

Now what i want is

df_skeleton

  col1 col2 col3 col4 col5 col6 col7 col8 col9 col10
0  23   0    45   0    0    0    10   0    0    0

Upvotes: 3

Views: 48

Answers (2)

piRSquared
piRSquared

Reputation: 294488

Use pandas.DataFrame.combine_first

df_skeleton.combine_first(df).fillna(0, downcast='infer')

   co6  col1  col10  col2  col3  col4  col5  col5  col7  col8  col9
0    0    23      0     0    45     0     0     0    10     0     0

Upvotes: 4

jezrael
jezrael

Reputation: 863226

Use reindex with parameter fill_value:

columns = ['col1','col2','col3','col4','col5','col5','co6','col7','col8','col9','col10']
df_skeleton = pd.DataFrame(columns=columns)

df = df.reindex(columns=df_skeleton.columns, fill_value=0)
print (df)
   col1  col2  col3  col4  col5  col5  co6  col7  col8  col9  col10
0    23     0    45     0     0     0    0    10     0     0      0

Upvotes: 4

Related Questions