How to verify null value in rows in a dataframe column?

Asked

Viewed 120 times

1

I’m looking to replace the null values with the value of the year.

Given the following dataframe :

year value
2000  1
NaN   2
NaN   3     
NaN   4
NaN   5
NaN   6  
2001  1
NaN   2
NaN   3     
NaN   4
NaN   5
NaN   6  
...
2020  1
NaN   2
NaN   3     
NaN   4
NaN   5
NaN   6 

The zero values between the years, for example 2000 and 2001 I would like to replace by 2000 until arriving in 2001 and so on. It should look something like this :

year value
2000   1
2000   2
2000   3     
2000   4
2000   5
2000   6
2001   1
2001   2
2001   3     
2001   4
2001   5
2001   6  
...
2020   1
2020   2
2020   3     
2020   4
2020   5
2020   6

I tried to do so:

tam = df["year"].size
val = df.iloc[0,0]
for i in range(tam):
    if df.iloc[i,0]==None:
        df.iloc[i,0]=val
    else:
        val = df.iloc[i,0]   
 

But the dataframe remains the same. It seems the if condition df.iloc[i,0]==None doesn’t work. In this sense how to check if an element of a column is null?

1 answer

1


You can use the fillna() with the forward Fill filling method'

df['year'].fillna(method = 'ffill', inplace = True)

Entree:

    year    value
0   2000     1
1   NaN      2
2   NaN      3
3   NaN      4
4   NaN      5
5   NaN      6
6   NaN      7
7   2001     8
8   NaN      9
9   NaN      10
10  NaN      11
11  NaN      12
12  NaN      13
13  2020     14

Exit:

    year    value
0   2000    1
1   2000    2
2   2000    3
3   2000    4
4   2000    5
5   2000    6
6   2000    7
7   2001    8
8   2001    9
9   2001    10
10  2001    11
11  2001    12
12  2001    13
13  2020    14
  • 1

    Perfect, I didn’t know that command. Thank you.

  • Speak Beto, good morning! For nothing! Hug!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.