the phoenix
the phoenix

Reputation: 739

Replace NAN values in a column from a data frame by unique values from a list?

I have a data frame with many NANs, I would like to replace these values as specific names from a list. The data frame:

index Color 
0      Red
1      Blue
2      NaN
3      NaN
4      NaN
5      Green
8      Yellow
....
165    Black 

The list :

L=[yellow1,yellow2,red2,red4....]

I tried the following code to try to replace the NAN with the list values, but it does not really work:

index_NAN=df[df.color.isna()].index
length=len(index_NAN)

for i,j,k in zip(df.index, index_NAN,L): 
    if(i == j):
               df.color.fillna(k,inplace=True)
    else: 
         continue

Upvotes: 0

Views: 820

Answers (1)

BENY
BENY

Reputation: 323326

Try .loc

L=['yellow1','yellow2','red2']
df.loc[df.Color.isna(),'Color'] = L
df
Out[115]: 
   index    Color
0      0      Red
1      1     Blue
2      2  yellow1
3      3  yellow2
4      4     red2
5      5    Green
6      8   Yellow

Upvotes: 3

Related Questions