TransWikia.com

Python DataFrame: How to replace Nan with value on one specific position

Stack Overflow Asked by Yiqing Wang on January 3, 2022

I am trying to replace NA value at a specific position with another value using pd.DataFrame.fillna(previous_value, value, inplace = True). Although it’s no error showing up in the running process, the original Na value hasn’t been replaced yet.

Data[pd.isnull(Data["gender"])]

Data Output:

enter image description here

Replace Code:

 Data.loc[[2956]]["gender"].replace(np.nan, "F",inplace = True)

Data after replacement

Data.loc[[2956]]

Dataset after replacement:

enter image description here

Any idea how it happened?

5 Answers

One method you can try is without using replace. When you know the index just assign the value you want Code:

Data.gender[2956]='F'

Answered by Pranjal dubey on January 3, 2022

Try this

    Data.loc[[2956]]["gender"].replace(None, "F",inplace = True)

Answered by NANDHA KUMAR on January 3, 2022

Dataframe.replace isn't meant to replace a value at a single position to begin with, but to replace all the values that correspond to something. So in your example, by using replace the best result you could have is having 'Scout Schultz' and 'Tk Tk' 's genders set to 'F'.

Since you know that the row 2956 has NaN in 'gender' column, you can do something like

data.loc[2956, 'gender'] = 'F'

Answered by Guil23 on January 3, 2022

When you get the value using column and row, you take the value, not that position in the dataframe. And you can't use replace() for a single value.

You can just change the value using:

 Data["gender"].loc[[2956]] = 'F'

Answered by Murilo Malek on January 3, 2022

You could just do this.

df.loc[2956,'gender'] = 'F'

Answered by rhug123 on January 3, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP