No_body
No_body

Reputation: 842

Group by and return all columns

My dataframe looks like

  c1   c2   c3
  1     2    A 
  1     3    B 
  1     5    NA 
  1     7    D
  2     0    E
  2     1    NA
  2     2    B 
  2     4    A 
  2     6    B

I want to fill the last column with bfill for each id.

   c1   c2   c3
  1     2    A 
  1     3    B 
  1     5    D
  1     7    D
  2     0    E
  2     1    B
  2     2    B 
  2     4    A 
  2     6    B

I tried

  df.groupby(['c1']).apply(lambda x:       
  x['c3'].fillna(method='bfill')).reset_index()

But it's missing column c2. How can I get the desired format.

Upvotes: 1

Views: 81

Answers (1)

d_kennetz
d_kennetz

Reputation: 5359

Just change the value of c3 to the result of the bfill:

df['c3'] = df.groupby(['c1'])['c3'].bfill()

output:

   c1  c2 c3
0   1   2  A
1   1   3  B
2   1   5  D
3   1   7  D
4   2   0  E
5   2   1  B
6   2   2  B
7   2   4  A
8   2   6  B

Upvotes: 2

Related Questions