Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through Pandas Column and replacing nan values

Tags:

I'm trying to replace missing values in a column with predicted values I have stored in a list.

This is an example of what I would like to accomplish:

    A   B   C
0  7.2 'b' 'woo'
1  nan 'v' 'sal'
2  nan 'o' 'sdd'
3  8.1 'k' 'trili'

My list would be something like:

list = [3.2, 1.1]

And my desired outcome is:

    A   B   C
0  7.2 'b' 'woo'
1  3.2 'v' 'sal'
2  1.1 'o' 'sdd'
3  8.1 'k' 'trili'

I've tried various different approaches towards this problem, but this code illustrates my general idea:

q = 0
for item in df['Age']:
    if str(item) == 'nan':
        item = my_list[q]
        q = q + 1

Thank you in advance. This has been driving me nuts for a while now.

like image 320
Juan R. Avatar asked Jun 10 '17 14:06

Juan R.


1 Answers

You can use isnull() in something like:

df.loc[pd.isnull(df['A']), 'A'] = mylist

Example:

In [19]: df
Out[19]: 
     A  B      C
0  7.2  b    woo
1  NaN  v    sal
2  NaN  o    sdd
3  8.1  k  trili

In [20]: mylist = [3.2, 1.1]

In [21]: df.loc[pd.isnull(df['A']), 'A'] = mylist

In [22]: df
Out[22]: 
     A  B      C
0  7.2  b    woo
1  3.2  v    sal
2  1.1  o    sdd
3  8.1  k  trili
like image 55
Lev Levitsky Avatar answered Oct 11 '22 14:10

Lev Levitsky