0

I have a dataframe that looks like this :

Contract N° 1-14 15-30 31-60
10001 NaN NaN 2500
10002 NaN 3500 NaN
10003 NaN NaN NaN
10004 1500 NaN NaN

I would like to loop through all rows of this dataframe and on each row, loop from right to left while the value of the cell is NaN and counting the number of NaN cells thus found, then add a column to write down the number of continuous NaN cells counted.

Contract N° 1-14 15-30 31-60 NaN Count
10001 NaN NaN 2500 0
10002 NaN 3500 NaN 1
10003 NaN NaN NaN 3
10004 1500 NaN NaN 2

I feel like I'm mindlessly trying to translate VBA array logic into this:

for i in df:
   While df[i,4-j] == 'NaN':
      df['NaN Count'] = df['NaN Count']+1
      j=j+1

I could not find a way to write a dataframe's cell coordinates as one would with a two-dimensional VBA array, kinda like df(i,j) so maybe this shouldn't be the way to go.

Any help would be greatly appreciated.

  • maybe you could explain a bit more about your answer. the number of null values per row? – sammywemmy Feb 19 '21 at 07:00
  • The number of null values per row, but counting right to left. If rightmost value is null then evaluate value to its left, then to its left and so forth until the entire row has been evaluated. – technikh Feb 19 '21 at 12:36

1 Answers1

0

Try this with pandas inbuilt methods -

df.isna().sum(1)
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
  • 1
    typo check dupe. – jezrael Feb 19 '21 at 06:59
  • Apologies, fixed. – Akshay Sehgal Feb 19 '21 at 07:00
  • Hi, thanks for your contribution but where I'm really struggling is the nested while loop where it starts by evaluating the rightmost value of each row. If that value is null, it moves on on to the value to its left, and so forth until it either encounters a non-null value or has evaluated the entire row. It then goes on to evaluate the next row. – technikh Feb 19 '21 at 12:41