简体   繁体   中英

SettingWithCopyWarning when trying to get elements not equal to list

I'm trying to remove everything in a dataframe not equal to elements in a list, but I'm getting the following warning:

C:/Users/jalco/PycharmProjects/project/main.py:119: 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
  df[sample'] = ''
C:/Users/jalco/PycharmProjects/project/main.py:120: 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
  df['sample'] = np.where((df['num'] > 0) &

Here is my code causing the warning:

if not config_dict['admin']:
    df = df[~df['transtype'].isin(transtype['admin'])]

if 'sample' in config_dict['links']:
    df['sample'] = ''
    df['sample'] = np.where((df['num'] > 0) &
                                    (df['transtype'] == df['coll']),
                                    df['num'], df['sample'])

My question is "is there a better way to drop the rows I don't need or do I just silence the warning manually?"

Thanks

I would add .copy() when actually creating df because that seems to be the root of the problem, and then you can try assigning the column with .loc[] . Also you can save a line of code, by simply using:

df.loc[:,'sample']  = np.where((df['num'] > 0) &
                                (df['transtype'] == df['coll']),
                                df['num'], ''])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM