Python: How can I get the previous 5 values in a Pandas dataframe after skipping the very last one? -
i have pandas dataframe, df follows:
0 1 2 0 k86e 201409 180 1 k86e 201410 154 2 k86e 201411 157 3 k86e 201412 153 4 k86e 201501 223 5 k86e 201502 166 6 k86e 201503 163 7 k86e 201504 169 8 k86e 201505 157
i know in order last 5 values of column 2, have do:
df[2].tail()
this return values 157, 169, 163, 166, 233
.
however, skip last value = 157 , last 5 values before 157 e.g. 169, 163, 166, 233, 153
.
how can this?
thanks in advance!
use negative indices , pass these iloc
slice rows of interest:
in [5]: df.iloc[-6:-1] out[5]: 0 1 2 3 k86e 201412 153 4 k86e 201501 223 5 k86e 201502 166 6 k86e 201503 163 7 k86e 201504 169
you can index col of interest using above:
in [6]: df.iloc[-6:-1]['2'] out[6]: 3 153 4 223 5 166 6 163 7 169 name: 2, dtype: int64
the following work uses ordinal position of column
df.iloc[-6:-1,2]
the syntax iloc
means iloc[start:end]
in case can pass negative index indicate want start 6th row end , end @ last row not include it, known open, closed interval.
there related so question slicing notation.
also python docs
Comments
Post a Comment