Square9627
Square9627

Reputation: 939

Python - IF for a column in panda dataframe

I would like to turn NaN values in the column GP in the dataframe draft (which has 22 rows) into 0. I tried these lines but they don't work

import pandas as pd
draft =  pd.read_csv('Draft year.csv')

if draft['GP'].isnull():
    draft['GP'] = 0

In R there is ifelse which does the job nicely but I dont know equivalent in python. Really appreciate any help

Upvotes: 0

Views: 83

Answers (2)

o-90
o-90

Reputation: 17585

You can use list comprehension and replace the NaNs with zeros.

draft['GP'] = [0 if np.isnan(x) else x for x in draft.GP]

Upvotes: 2

Yarnspinner
Yarnspinner

Reputation: 882

The .fillna function works for this, you can specify the 'draft' series first if u only want to fillna with 0 for that column. Example below:

import pandas as pd

print data3
data3 = pd.read_csv("data2.csv")
data3["Name"].fillna(0, inplace = True)
data3

  Name Name2  Time
0  NaN   NaN     1
1  NaN   NaN     2
2   G     G      3

  Name Name2  Time
0    0   NaN     1
1    0   NaN     2
2   G     G      3

Upvotes: 5

Related Questions