18

Say I have the following dataframe, and I want to change the two elements in column c that correspond to the first two elements in column a that are equal to 1 to equal 2.

>>> df = pd.DataFrame({"a" : [1,1,1,1,2,2,2,2], "b" : [2,3,1,4,5,6,7,2], "c" : [1,2,3,4,5,6,7,8]})
>>> df.loc[df["a"] == 1, "c"].iloc[0:2] = 2
>>> df
   a  b  c
0  1  2  1
1  1  3  2
2  1  1  3
3  1  4  4
4  2  5  5
5  2  6  6
6  2  7  7
7  2  2  8

The code in the second line doesn't work because iloc sets a copy, so the original dataframe is not modified. How would I do this?

1

2 Answers 2

6

A dirty way would be:

df.loc[df[df['a'] == 1][:2].index, 'c'] = 2
2
  • 2
    I don't think this is dirty! This is an example of a class of slicing where it's positional along one axis, and by index on the other.
    – piRSquared
    Commented Jun 20, 2016 at 0:21
  • 4
    I was able to save one char: df.loc[df.index[df.a == 1][:2], 'c'] = 2
    – piRSquared
    Commented Jun 20, 2016 at 0:27
2

You can use Index.isin:

import pandas as pd

df = pd.DataFrame({"a" : [1,1,1,1,2,2,2,2], 
                   "b" : [2,3,1,4,5,6,7,2],
                   "c" : [1,2,3,4,5,6,7,8]})

#more general index                       
df.index = df.index + 10
print (df)
    a  b  c
10  1  2  1
11  1  3  2
12  1  1  3
13  1  4  4
14  2  5  5
15  2  6  6
16  2  7  7
17  2  2  8

print (df.index.isin(df.index[:2]))
[ True  True False False False False False False]

df.loc[(df["a"] == 1) & (df.index.isin(df.index[:2])), "c"] = 2
print (df)
    a  b  c
10  1  2  2
11  1  3  2
12  1  1  3
13  1  4  4
14  2  5  5
15  2  6  6
16  2  7  7
17  2  2  8

If index is nice (starts from 0 without duplicates):

df.loc[(df["a"] == 1) & (df.index < 2), "c"] = 2
print (df)
   a  b  c
0  1  2  2
1  1  3  2
2  1  1  3
3  1  4  4
4  2  5  5
5  2  6  6
6  2  7  7
7  2  2  8

Another solution:

mask = df["a"] == 1
mask = mask & (mask.cumsum() < 3)

df.loc[mask.index[:2], "c"] = 2
print (df)
   a  b  c
0  1  2  2
1  1  3  2
2  1  1  3
3  1  4  4
4  2  5  5
5  2  6  6
6  2  7  7
7  2  2  8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.