0

This question was answered here. Yet, having the following input:

print(type(df1))
df1['x'] = np.nan

I got the following output:

<class 'pandas.core.frame.DataFrame'>
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:2: SettingWithCopyWarning:


A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

How my case could be different from the one in the attached link?

Gideon Kogan
  • 662
  • 4
  • 18

1 Answers1

1

The true reason for this warning is likely a few lines of code back, when you create df1. If you have something like this:

df1 = another_df[['col1', 'col2']]

Sometimes you get a slice of the original data frame, other times you get a copy. It's not easy to tell what you get. I believe it has something to do with value vs. reference semantics in the original frame.

To get rid of the warning, make an explicit copy:

df1 = another_df[['col1', 'col2']].copy()
df1['new_col'] = np.na
Code Different
  • 90,614
  • 16
  • 144
  • 163