Home > OS >  python - how do I perform the specific operation in dataframe
python - how do I perform the specific operation in dataframe

Time:08-20

This is my dataframe

import pandas as pd
df = pd.DataFrame({'3a': [-23, 12, -12, 10, -23, 12, -32, 15, -20, 10],
                   '4b': [-30, 20, -21, 15, -33, np.nan, np.nan, np.nan, np.nan, np.nan],
                   '5c': [-40, 25, -26, 19, -39, np.nan, np.nan, np.nan, np.nan, np.nan],
                   '6d': [-45, 34, -29, 25, -53, np.nan, np.nan, np.nan, np.nan, np.nan],
},index= ['A1','A2','A3','A4','A5','A6','A7','A8','A9','A10'])

How do I replace the np.nans in row A6 and A7 with the values in below dataframe

df1 = pd.DataFrame([[1,2,3],[3,4,5]],index=['A6','A7'],columns=['4b', '5c', '6d'])

CodePudding user response:

you can update update, since the index is matching in the two DF, the null values will get updated with the ones from df1 into df.

use overwrite=false, to only update the NaN values

df.update(df1,overwrite=False)
     3a        4b      5c     6d
A1  -23     -30.0   -40.0   -45.0
A2   12      20.0    25.0    34.0
A3  -12     -21.0   -26.0   -29.0
A4   10      15.0    19.0    25.0
A5  -23     -33.0   -39.0   -53.0
A6   12       1.0     2.0     3.0
A7  -32       3.0     4.0     5.0
A8   15       NaN     NaN     NaN
A9  -20       NaN     NaN     NaN
A10  10       NaN     NaN     NaN
  • Related