DGraham
DGraham

Reputation: 715

Fill blank cells from previous columns pandas python

If I have a simple dataframe such as:

q_1     q_1_mark    q_2    q_2_mark
TRUE    a           1      c
FALSE   b           2   
TRUE    c           3   

How could I fill in the blank values of the q_2_mark column, so they matched with q_1_mark? So the steps would be:

  1. Look into the column and find the blank values.
  2. Look into the previous _mark column and bring across the value for only the blank cells.

I can do brute force copy and paste style formatting, but this loses any cells that contain anything different from the previous column, i.e a --> c

Upvotes: 1

Views: 1701

Answers (2)

Alexander
Alexander

Reputation: 109526

df.q_2_mark.fillna(df.q_1_mark, inplace=True)

df
     q_1 q_1_mark  q_2 q_2_mark
0   True        a    1        c
1  False        b    2        b
2   True        c    3        c

Upvotes: 4

piRSquared
piRSquared

Reputation: 294228

Assuming your dataframe is df, Try:

df.q_2_mark = df.q_2_mark.combine_first(df.q_1_mark) 

     q_1 q_1_mark  q_2 q_2_mark
0   True        a    1        c
1  False        b    2        b
2   True        c    3        c

Upvotes: 2

Related Questions