Can we set another value to take place of missing values instead of None or nan?

Question

In the context of this exercise, can we set another value to take place of missing values instead of None or nan?

Answer

After performing an outer merge, missing values will become filled with None or nan by default, and there is no way to set another value during this step.

After the merge, replacing these is a bit easier. You can utilize the fillna() method, which will replace all missing or nan values with another value you specify.

# Replaces all nan values with 0
df.fillna(0, inplace=True)
3 Likes

Thanx was just wondering that @jephos249

1 Like

What If I want to fill the nan with different values in the table?
For example, I want to fill the first row nan with 6 and the second row nan with 5…
How do I accomplish that?
Thanks

1 Like

Hi, you may try this:

df['column name'] = df['column name'].replace(['old value'],'new value')

source: https://datatofish.com/replace-values-pandas-dataframe/

1 Like

I tried using this method to replace nan value with a new value but it doesn’t work.

Can you show me the actual code?

newcode = store_a_b_outer['store_b_inventory'].replace(['nan'], '88'), inplace=True)

Thank you

Hi raysonng,
the code is like below:

store_a_b_outer['store_b_inventory'] = store_a_b_outer['store_b_inventory'].replace([float("NaN")],'0')

because nan is not a string/ numbers, special treatment is to make (I am not sure the technical jargons, if need one could help provide)

2 Likes

its just ‘nan’ no need of square brackets

Similar question but can we also replace ‘nan’ with different values for different rows? for example row 1 and 3 on the outer table I want to replace ‘nan’ with 2 different values?

A post was split to a new topic: What are the differences between inner merge and outer merge?

When I applied the fillna() method to a df=table, I got None as a result.
In the context of this exercise,

store_a_b_outer.fillna(0, inplace=True) return None

Instead, by applying the mfillna() method to each column:

store_a_b_outer.store_a_inventory.fillna(0, inplace=True)
store_a_b_outer.store_b_inventory.fillna(0, inplace=True)

all the nan values where replaced by 0 in the store_a_b_outer dataframe.

See if this helps.

Replace all NaN values with 0:

store_a_b_outer.fillna(0, inplace=True)
print(store_a_b_outer)

Replace NaN values only in store_b_inventory with 0:

store_a_b_outer['store_b_inventory'] = store_a_b_outer['store_b_inventory'].replace(float('nan'), 0)
print(store_a_b_outer)

Replace cell value in the store_b_inventory, row index 1, with 0:

store_a_b_outer.at[1, 'store_b_inventory'] = 0
print(store_a_b_outer)