0

I am trying first to slice a some columns from original dataframe and then add the additional column 'INDEX' to the last column.

    df = df.iloc[:, np.r_[10:17]]  #col 0~6
    df['INDEX'] = df.index  #col 7

I have the error message of second line saying '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'
Why am I seeing this and how should I solve it?

chen abien
  • 257
  • 1
  • 6

2 Answers2

0

I would do

df.loc[:,'INDEX'] = df.index
Philip Egger
  • 326
  • 1
  • 11
0

by default Python does shallow copy of dataframe. So whatever operations are performed on dataframe, it will actually performed on originall data frame. and the message is exactly indicates that.

Either of below will make the Python interpreter happy :

df = df.iloc[:, np.r_[10:17]].copy()

or

df.loc[:, ['INDEX']] = df.index