Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filling a NaN column by another column content in pandas dataframe

Tags:

python

pandas

I have a dataframe with a column having lots of NaN values. I need to updates these values by another column values when NaN is in the column.

    One    Two
0    10    21

1    11    NaN

2    12    25

I want a result like this

    One    Two

0    10    21

1    11    **11**

2    12    25

Please help me for the synthaxe of slicing in the column two and have Nafill detection to copy the value from column One.

This is the code to create the 1rst matrix :

 df = pd.DataFrame({'One' : [10, 11, 12], 'Two' : [21, np.NAN, 25]})
like image 572
Denis Cottin Avatar asked Oct 20 '25 11:10

Denis Cottin


1 Answers

You can use fillna using that column:

In [4]: df['Two'].fillna(df['One'])
Out[4]:
0    21
1    11
2    25
Name: Two, dtype: float64

So to actually change the column: df['Two'] = df['Two'].fillna(df['One'])

like image 132
joris Avatar answered Oct 23 '25 00:10

joris