简体   繁体   中英

Try using .loc[row_indexer,col_indexer] error even after using .loc

I am simply trying to multiply two columns of a dataframe and save the results into a new column like this,

df.loc[:,'sales'] = df['Quantity']*df['UnitPrice']

I am getting the following error even though I am using .loc for the new column! Any idea what I am missing?

/var/folders/qp/lp_5yt3s65q_pj__6v_kdvnh0000gn/T/ipykernel_39035/1010072081.py:3: 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.loc[:,'sales'] = df['Quantity']*df['UnitPrice']

我希望这对你有用:

df.assign(sales=lambda df: df.Quantity * df.UnitPrice)

Thanks for the comments. Like what @Quang Hoang mentioned, this is because I was forgetting to use .copy() to created this smaller DataFrame earlier in the code.

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