Python pandas 使用dataframe操作时出现警告
Python pandas appear warning when use dataframe operation
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]
当我使用代码时,我的控制台中有两个警告。
__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
我知道警告的意思,但是如何更改我的代码以避免这些警告?
这与 SettingWithCopyWarning 有关,同样在 pandas 中,对于这种情况,我们通常有多种方式而不是 for 循环
np.where
final_merge['user_ID']=np.where(final_merge['user_x']=='nan',final_merge['user_y'],final_merge['user_x'])
或fillna
,如果nan
是np.nan,如果不是final_merge['user_x'].replace('nan',np.nan, inplace=True)
final_merge['user_ID']=final_merge['user_x'].fillna(final_merge['user_y'])
或mask
final_merge['user_ID']=final_merge['user_x'].mask(final_merge['user_x']=='nan',final_merge['user_y'])
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]
当我使用代码时,我的控制台中有两个警告。
__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
我知道警告的意思,但是如何更改我的代码以避免这些警告?
这与 SettingWithCopyWarning 有关,同样在 pandas 中,对于这种情况,我们通常有多种方式而不是 for 循环
np.where
final_merge['user_ID']=np.where(final_merge['user_x']=='nan',final_merge['user_y'],final_merge['user_x'])
或fillna
,如果nan
是np.nan,如果不是final_merge['user_x'].replace('nan',np.nan, inplace=True)
final_merge['user_ID']=final_merge['user_x'].fillna(final_merge['user_y'])
或mask
final_merge['user_ID']=final_merge['user_x'].mask(final_merge['user_x']=='nan',final_merge['user_y'])