user2082695
user2082695

Reputation: 250

Modifying values with conditions

I am facing a problem quite similar to the one explained in the documentation. This code works but raises a warning:

In [296]: dfb = DataFrame({'a' : ['one', 'one', 'two',
   .....:                         'three', 'two', 'one', 'six'],
   .....:                  'c' : np.arange(7)})
   .....: 
   # This will show the SettingWithCopyWarning
   # but the frame values will be set
   In [297]: dfb['c'][dfb.a.str.startswith('o')] = 42

Is there anyway to implement the same behaviour based in a filter without raising the warning?

Upvotes: 1

Views: 33

Answers (1)

EdChum
EdChum

Reputation: 394159

Use loc, place the boolean condition within the square brackets [] and the column of interest after the comma so you are not performing chained indexing:

In [40]:

dfb.loc[dfb.a.str.startswith('o'),'c'] = 42
dfb
Out[40]:
       a   c
0    one  42
1    one  42
2    two   2
3  three   3
4    two   4
5    one  42
6    six   6

Upvotes: 1

Related Questions