Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, pandas dataframes. pd.fillna() for specific columns with specific values

For example dataframe like this:

| 1  6   nan ... |
| 1  nan 5   ... |
|nan 2   4   ... |
|... ... ... ....

I want to use values from list [11, 12, 13 ...] to fill nan with the values from list. So, 10 for nans from first column, 12 for second etc. Is there a way to do this without using .hstack() combined with df[column].fillna(value)?

like image 768
Andrey Izmaylov Avatar asked Dec 15 '25 20:12

Andrey Izmaylov


1 Answers

You can pass a Series to DataFrame.fillna; the columns of the DataFrame are aligned with the index of the Series:

import numpy as np
import pandas as pd
nan = np.nan

df = pd.DataFrame({'A':[1,1,nan],'B':[6,nan,2],'C':[nan,5,4]})
ser = pd.Series([11,12,13], index=list('ABC'))
print(df.fillna(ser))

yields

      A     B     C
0   1.0   6.0  13.0
1   1.0  12.0   5.0
2  11.0   2.0   4.0
like image 157
unutbu Avatar answered Dec 17 '25 11:12

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!