Home > Enterprise >  Problem when modifying a copy of slice from DataFrame. (feat. numpy.where)
Problem when modifying a copy of slice from DataFrame. (feat. numpy.where)

Time:11-16

Why does warning occur when modifying a copy of Pandas.dataframe? And why doesn't warning occur when modifying using numpy.where? (df = DataFrame Object)

Warning Code

[186] df = input_df.copy()
[187] df['trade_status'][df['trade_status'] == 'DONE'] = 'FILLED'
---------------------------------------------------------------------------
C:\Practice\Report\src\service\ReportService.py:187: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

No Warning Code

[186] df = input_df.copy()
[187] df['trade_status'] = np.where(df['trade_status'] == 'DONE', 'FILLED', df['trade_status'])
---------------------------------------------------------------------------
Clear

CodePudding user response:

The result of df = input_df.copy() is indeed a new DataFrame. In this point you are right.

But you don't operate on it directly. Note that df['trade_status'][df['trade_status'] == 'DONE'] creates a view of df.

So when you attempt to save a new value there (… = 'FILLED'), the exception is raised.

  • Related