2

Question: Given DataFrame b, how can I replace the values of multiple columns, with one value, through boolean mask column identification?

What works, but I don't want:

b.iloc[:, 2:6] = "someConstantValue"

What doesn't work, but I want:

b.iloc[:, 2:6][b["columnA"] == "someCondition"]] = "someConstantValue"

Thanks for your time!

2 Answers 2

3

You can use iloc with Boolean indexing, but be careful. It works with Boolean arrays, not Boolean series. For example:

b.iloc[(b['A'] == 'a').values, 2:6] = 'someConstantValue'

As an aside, chained indexing is explicitly discouraged in the docs. There should never be a need to use chained indexing.

Sign up to request clarification or add additional context in comments.

8 Comments

10 secs late ;]
"100 loops, best of 3: 2.65 ms per loop". Too late bud ;)
Could you elaborate further concerning chain indexing?
Also, how does your solution filter for multiple conditions of 'A'?
Not sure what you mean. Your example and jezrael's solution, as well as mine, all filter for a single condition only.
|
2

You have to use DataFrame.loc and for columns names by positions use indexing by b.columns[2:6].

b = pd.DataFrame({'A':list('abaaef'),
                   'B':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'D':[1,3,5,7,1,0],
                   'E':[5,3,6,9,2,4]})

print (b)
   A  B  C  D  E
0  a  4  7  1  5
1  b  5  8  3  3
2  a  4  9  5  6
3  a  5  4  7  9
4  e  5  2  1  2
5  f  4  3  0  4

b.loc[b["A"] == "a", b.columns[2:6]] = 100
print (b)
   A  B    C    D    E
0  a  4  100  100  100
1  b  5    8    3    3
2  a  4  100  100  100
3  a  5  100  100  100
4  e  5    2    1    2
5  f  4    3    0    4

1 Comment

"100 loops, best of 3: 3.26 ms per loop". Compared to @ysearka "100 loops, best of 3: 2.98 ms per loop", with modification on his/her response. Check comment.

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.