user12941222
user12941222

Reputation:

modify values of a pandas column that contains nan

I have't find questions like mine...

btw I have a df with a column Year like this:

    2009)
    1998)
    2000)
    1980)
    2002)
    nan
    nan
    nan
    2014)
    1973)
    nan

I want to cut off the parenthesis, but when I use data['Year'] = data['Year'][:-1] nothing happens (not even errors)

If I use data['Year'] = data['Year'].apply(lambda x: x[:-1]) it gives me

TypeError: 'float' object is not subscriptable

I guess that the problem are "nan" values, but how can I fix the problem?
It should be ok to convert nans in 0.

thanks a lot

Upvotes: 0

Views: 85

Answers (3)

wwnde
wwnde

Reputation: 26676

Try string replace and chain fillna to remove NaNa

df.Year=df.Year.str.replace('[\(\)]','').fillna(0)

enter image description here

Upvotes: 1

Adrien Matissart
Adrien Matissart

Reputation: 1690

Pandas implements a .str property to manipulate text data.

data['Year'] = data['Year'].str[:-1]

Upvotes: 0

Arhiliuc Cristina
Arhiliuc Cristina

Reputation: 323

I usually do something like this:

data['Year'] = data['Year'].apply(lambda x: x[:-1] if isinstance(x, str) else '')

After else you can put what value you want to appear if it's not a string.

Upvotes: 0

Related Questions