Python: How can I get the previous 5 values ​​in a Pandas frame after skipping the last?

I have a Pandas dataframe, df as 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 that in order to get the last 5 values, for example, column 2, I have to do:

df[2].tail()

This will return the values 157, 169, 163, 166, 233.

However, I would like to skip the last value, which is = 157, and get the last five values ​​up to 157, for example. 169, 163, 166, 233, 153.

How can i do this?

Thanks in advance!

+4
source share
2 answers

Use negative indices and pass them in ilocto slice lines 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

Then you can index the code of interest using the above:

In [6]:

df.iloc[-6:-1]['2']
Out[6]:
3    153
4    223
5    166
6    163
7    169
Name: 2, dtype: int64

:

df.iloc[-6:-1,2]

iloc iloc[start:end], , , , , , .

SO .

python

+5
df.iloc[-6:-1,2]
Out[54]: 
3    153
4    223
5    166
6    163
7    169

:

df.iloc[-6:-1,2].values
Out[64]: array([153, 223, 166, 163, 169], dtype=int64)
+3

All Articles