Pandas setting limited subset

Viewed 44

I want to set the first N rows of a pandas dataframe that satisfy a condition. Eg for:

data = {'id':[1,1,2,2,2,4,2,2], 'val':[9,9,9,9,9,9,9,9]}
df = pd.DataFrame(data)

If I do:

df.loc[df.id == 2] = None

I set all rows with id == 2, but I only want to set N of them.

I've tried

df.loc[df.id == 2][range(N)] = None

but to no avail.

Is there any way to do this, without using loops?

1 Answers

IIUC, use pandas.DataFrame.loc twice. Not so pretty, but works:

df.loc[df.loc[df["id"].eq(2)].index[:2]]=None
print(df)

Output:

    id  val
0  1.0  9.0
1  1.0  9.0
2  NaN  NaN
3  NaN  NaN
4  2.0  9.0
5  4.0  9.0
6  2.0  9.0
7  2.0  9.0
Related