Juan R.
Juan R.

Reputation: 53

Iterating through Pandas Column and replacing nan values

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.

Upvotes: 5

Views: 4134

Answers (2)

piRSquared
piRSquared

Reputation: 294488

n = iter([3.2, 1.1])
for i, j in zip(*np.where(df.isnull())):
    df.set_value(i, j, next(n), True)

df

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

Upvotes: 1

Lev Levitsky
Lev Levitsky

Reputation: 65811

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

Upvotes: 3

Related Questions