2

i am using the answer from Pandas SettingWithCopyWarning in my script but it returned me 'SettingWithCopyWarning', may i know how should i fix it?

attemped1: dff['changed'] = dff.col1.ne(dff.col1.shift(1)) attemped2: dff.loc[:, 'changed] = dff.col1.ne(dff.col1.shift(1))

0

1 Answer 1

3

Your code is correct, problem is in some line above.

I guess you filter your DataFrame and solution is add copy:

dff = df[df['col2'] == 1].copy()
dff['changed'] = dff.col1.ne(dff.col1.shift(1))

If you modify values in dff later you will find that the modifications do not propagate back to the original data (df), and that Pandas does warning.

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

4 Comments

is it true that without copy() will modify original dataframe? i don't see the effect in the test case below? df = pd.DataFrame({'col1':['A', 'B', 'C'], 'col2':[111,222,333], 'col3':['aaa', 'bbb', 'aaa']}) dff = df[df.col3 == 'aaa'] dff.loc[0, 'col3'] = 'zzz'
@user466130 - Give me a sec.
@user466130 - No, there is no modification in original df. It is warning, because possible chaining indexing. Also check this for explanation with sample data.
@user466130 - Also there are another way for turn off this warning, pd.options.mode.chained_assignment = None

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.