Iterate through Pandas Column and replace nan values

I am trying to replace missing values ​​in a column with predicted values ​​that I saved 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 will look something like this:

list = [3.2, 1.1]

And my desired result:

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

I tried different approaches to 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

Thanks in advance. It made me dunk for a while.

+4
source share
2 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
+2
source
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
+1
source

Source: https://habr.com/ru/post/1678947/


All Articles