Reputation: 4442
I have dataframe and there are NaN
values:
col1 col2 col3
234 NaN 1
NaN NaN 18
9 2 NaN
I have list with values [12, 15, 3] and I need to fill this columns:
Desire output
col1 col2 col3
234 15 1
12 15 18
9 2 3
I can do it with
for (col, mean) in zip(df.columns, means):
df[col].fillna(mean, inplace=True)
But is any way to do it without loop?
Upvotes: 1
Views: 946
Reputation: 30424
Yet another approach:
df.fillna( pd.Series( [12, 15, 3], index=df.columns ) )
It looks like you may want the mean of each column (?), in which case you could just do:
df.fillna( df.mean() ) # df.mean() returns a series
In any event, the key to this answer and the others is just to give some sort of labelled output to fillna. Here I'm using a series whereas the other answers use dictionaries. Either approach is fine, of course, just depends on which is more convenient for you.
Upvotes: 4
Reputation: 3247
You can convert your list to a dictionary and give fillna a dictionary as an argument:
df.fillna({'col1': 12,'col2': 15, 'col3':3}, inplace=True)
Upvotes: 2
Reputation: 323266
Build a dict of those , then fillna
l1= [12, 15, 3]
df.fillna(dict(zip(df.columns,l1)))
Out[120]:
col1 col2 col3
0 234.0 15.0 1.0
1 12.0 15.0 18.0
2 9.0 2.0 3.0
Upvotes: 4