2

Hi there I'm a newbie in python learning through notebook, I have given iris dataset through .csv file and asked to replace one of the column values in some particular rows to NaN.I have tried "fillna" functions and "replace" functions but I'm not successful.Here is my code:

import pandas as pd
import numpy as np
from numpy import nan as NaN
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = pd.read_csv(url)
iris.columns = ['sepal_length','sepal_width','petal_length','petal_width','class']
iris.columns

#iris

iris.petal_length.fillna(np.nan)
iris1=iris.iloc[10:30]
print (iris1)
#bool_series = pd.isnull(iris['petal_length'])
#print (df)
Roy2012
  • 9,953
  • 2
  • 17
  • 32
  • Welcome to SO. Please read https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples, and include input and expected output *as text) in the question. – Roy2012 Jul 27 '20 at 12:38
  • A csv file is a **text** file and only representations are stored in it. What representation do you expect for NaN values? Just empty fields... – Serge Ballesta Jul 27 '20 at 12:40
  • 1
    Does this answer your question? [Pandas Replace NaN with blank/empty string](https://stackoverflow.com/questions/26837998/pandas-replace-nan-with-blank-empty-string) – balandongiv Jul 27 '20 at 12:44
  • I already answered below, but @balandongiv linked answer should also answer your question, and it has good examples. – SirMizou Jul 27 '20 at 13:07

2 Answers2

2

Looks like the problem is, that you are not saving the resulting DataFrame from .fillna() or .replace(). By default, those methods return new DataFrame object. To fix this either save the result to a variable or use inplace=True argument in your replace() or fillna() calls.

SirMizou
  • 78
  • 2
  • 4
1

I think you can use:

This replaces <some_value> with np.nan for the petal_length column

irirs.petal_length.replace(<some_value>, np.nan)

This will replace the rows where petal_length is equal to <some_value>

irirs[irirs.petal_length == <some_value>] = np.nan
cristian hantig
  • 780
  • 5
  • 11