0
final_merge['user_ID']=''
for i in range(len(final_merge)):
    if final_merge.loc[i,'user_x']=='nan':
        final_merge['user_ID'][i]= final_merge['user_y'][i]
    else:
        final_merge['user_ID'][i]= final_merge['user_x'][i]

When I use code,there are two warnings in my console.

__main__:6: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
__main__:4: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

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

I know the warning mean,but how to change my code to avoid these warning?

disney82231
  • 189
  • 1
  • 3
  • 11
  • try final_merge.loc[i, 'user_ID']? But definitely agree with @WeNYoBen below. With pandas there's much more to do than a loop – aprilangel Nov 04 '19 at 03:22

1 Answers1

2

This is related to SettingWithCopyWarning , Also in pandas we usually have multiple way rather than for loop for this type of case

np.where

final_merge['user_ID']=np.where(final_merge['user_x']=='nan',final_merge['user_y'],final_merge['user_x'])

Or fillna, if nan is np.nan, if not do final_merge['user_x'].replace('nan',np.nan, inplace=True)

final_merge['user_ID']=final_merge['user_x'].fillna(final_merge['user_y'])

Or mask

final_merge['user_ID']=final_merge['user_x'].mask(final_merge['user_x']=='nan',final_merge['user_y'])
BENY
  • 317,841
  • 20
  • 164
  • 234