Home > database >  Updating index values on nan values from another index
Updating index values on nan values from another index

Time:01-11

I have a df:

            2020        2021        2022        2023

A           50          60          nan         nan
A.2         50          60          0           0     # alternate version
B           500         600         0.7         0.8

I am trying to update the nan values on A from B so that the result would look like this:

            2020        2021        2022        2023

A           50          60          700         800

I tried:

df.loc['A'] = df.loc['A'].fillna(df.loc['B']*1000) # need to multiply the value by a 1000 before updating

But the values on A do not change, where is my mistake?

CodePudding user response:

Here is problem nan are strings, not np.nan:

#convert columns to numeric
df = df.astype(float)
#alternative if first method failed
df = df.apply(pd.to_numeric, errors='coerce')

df.loc['A'] = df.loc['A'].fillna(df.loc['B']*1000)
print (df)
    2020   2021   2022   2023
A   50.0   60.0  700.0  800.0
B  500.0  600.0    0.7    0.8

For converting row separately:

df.loc['A'] = df.loc['A'].astype(float).fillna(df.loc['B']*1000)
  •  Tags:  
  • Related