Humble Hero
Humble Hero

Reputation: 145

Updating values in Dataframe in a certain number of rows

I've got a dataframe

d={'Col1':['a','b','c','e','f','g','a','b','c','d'],'Col2':[3,4,6,None,7,8,None,9,None,None,]}
    df=pd.DataFrame(data=d)

what I need is to set values where Col2 is equal NaN: first three = 100

normally I would use loc for such tasks but for reasons I don't understand it does not work with loc+iloc:

df.loc[df.Col2.isnull()].iloc[:3]=100

Upvotes: 2

Views: 40

Answers (1)

jezrael
jezrael

Reputation: 863801

It seems you need fillna with parameter limit:

df['Col2'] = df['Col2'].fillna(100, limit=3)
print (df)
  Col1   Col2
0    a    3.0
1    b    4.0
2    c    6.0
3    e  100.0
4    f    7.0
5    g    8.0
6    a  100.0
7    b    9.0
8    c  100.0
9    d    NaN

If want use loc get first 3 indices of NaNs and set value:

idx = df.index[df.Col2.isnull()]
df.loc[idx[:3], 'Col2'] = 100

Upvotes: 1

Related Questions