1

I have a Dataframe as shown below

   A   B   C      D
0  1   2   3.3   4
1 NaT NaN NaN NaN
2 NaT NaN NaN NaN
3  5   6   7      8
4 NaT NaN NaN NaN
5 NaT NaN NaN NaN
6  9   1   2      3 
7 NaT NaN NaN NaN
8 NaT NaN NaN NaN

I need to copy the first row values (1,2,3,4) till the non-null row with index 2. Then, copy row values (5,6,7,8) till the non-null row with index 5 and copy (9,1,2,3) till row with index 8 and so on. Is there any way to do this in Python or Pandas. Quick help appreciated! Also is necessary not replace column D

Column C ffill gives 3.3456 as value for next row

Expected Output:

 A B C     D
0 1 2 3.3 4
1 1 2 3.3 NaN
2 1 2 3.3 NaN
3 5 6 7 8
4 5 6 7 NaN
5 5 6 7 NaN
6 9 1 2 3 
7 9 1 2 NaN
8 9 1 2 NaN
Avinash
  • 533
  • 5
  • 15

1 Answers1

2

Question was changed, so for forward filling all columns without D use Index.difference with ffill for columns names in list:

cols = df.columns.difference(['D'])

df[cols] = df[cols].ffill()

Or create mask for all columns names without D:

mask = df.columns != 'D'

df.loc[:, mask] = df.loc[:, mask].ffill()

EDIT: I cannot replicate your problem:

df = pd.DataFrame({'a':[2114.201789, np.nan, np.nan, 1]})

print (df)
             a
0  2114.201789
1          NaN
2          NaN
3     1.000000

print (df.ffill())
             a
0  2114.201789
1  2114.201789
2  2114.201789
3     1.000000
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252