adele adele - 13 days ago 6
Python Question

Value from previous week in new column

I have the following dataframe:

Open High Low Last Vol_POC Week
Timestamp
2016-09-27 02:00:00 165.50 165.58 165.46 165.47 165.98 39
2016-09-27 03:00:00 165.47 165.65 165.46 165.63 165.98 39
2016-09-27 04:00:00 165.64 165.92 165.59 165.91 165.98 39
2016-09-27 05:00:00 165.91 166.13 165.91 165.97 165.98 39
2016-09-27 06:00:00 165.98 165.98 165.76 165.78 165.98 39
2016-09-27 07:00:00 165.79 166.04 165.79 166.02 165.98 39


The
Week
value was created using this code:

data['Week']=[r.week for r in data.index]


I now want a new column
Vol_POC_last_week
giving the value for
Vol_POC
of the previous week. So for example, any row with
Week
value
40
I would have the
Vol_POC
value for
Week
39
etc.

Can you please show how I would do this?

Answer

I would do it this way:

data["Vol_POC_last_week"] = pd.Series()                                               
data.loc[data.Week == 40, "Vol_POC_last_week"] = data.loc[data.Week == 39, "Vol_POC"].values

pandas.DataFrame.loc

DataFrame.loc Purely label-location based indexer for selection by label.

The .loc attribute is the primary access method gives access to a value not to a copy of it.

It has simple and obvious interface:

.loc[row_indexer,column_indexer]

Multi line change

for i in data.Week.unique()[:-1]:
    data.loc[data.Week == i, "Vol_POC_last_week"] = data.loc[data.Week == i-1, "Vol_POC"].values

Since we need to make changes according to a particular value of Week column and it is not unique the only way I see now is just the same but iterative.