0

I have difficulties to understand why calling this function:

def my_function(df):
  df['column_C'] = df.groupby(['column_A'])['column_B'].shift(-1)
  return df

new_df = my_function(df)

Gives me the following warning:

<command-3554451885069750>:9: 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['column_C'] = df.groupby(['column_A'])['column_B'].shift(-1)

While executing the same operation outside the function does not:

df['column_C'] = df.groupby(['column_A'])['column_B'].shift(-1)

Could somebody explain why this happens and how to fix this?

sampeterson
  • 317
  • 1
  • 9

0 Answers0