Search code examples
pythonpandasdataframetime-seriesfinance

python pandas dataframe to make r(t-1).iloc[1:] = r(t).iloc[0:-1]


I want to make a column of a data frame of pandas, the second row to the last row equal to another column's first row to the second last row: it look like:

r(t-1).iloc[1:] = r(t).iloc[0:-1](r(t) and r(t-1)) 

are columns of the same data frame

the problem I met is python wouldn't get my idea that I want to shift of row of copying data :

IR['r(t-1)'].iloc[1:] = IR['r(t)'].iloc[0:-1]
/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py:190: 

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

  self._setitem_with_indexer(indexer, value)

any one know how to deal with it?


Solution

  • Welcome to SO.

    How to solve your problem

    It seems you need a shift in one of your columns. as the first two lines of your question indicate. you can do it by shift() method for pandas dataframes. Then your answer could possibly would be:

    df['new_row'] = df['old_row'].shift(1)
    

    You can shift forward or backward with negative and positive values of shifting

    What is the error you have ran into

    Briefly speaking, pandas has provided ways of data frame writing and reading, and it does not actually accept any other kind of doing that. The warning shows that you are not using a good way (in pandas humble opinion!) of writing to the dataframe (using iloc) as iloc is mostly used for accessing to rows by index.

    Any pandas expert here, please correct me if I am wrong.