Problem: Select first N rows and last row in Python Pandas.
only gets 1 row which is index 9 and last row.
df.iloc[[(9),-1]]
I thought I could get using head and last row but not working.
df.iloc[[head(9),-1]]
Target output: 0 1 2 3 up to 9 last row
CodePudding user response:
head = df.head(9)
tail = df.tail(1)
df = head.append(tail)
I think you just want this. Please clarify if this is wrong.
Output:
first_column second_column
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
12 12 12
This is assuming I understand correctly, you want 9 rows and also the last.
CodePudding user response:
You could use numpy.concatenate
:
import numpy as np
out = df.iloc[np.r_[0:9, -1]]
or just list concatenation:
out = df.iloc[list(range(9)) [-1]]
Test:
For a DataFrame:
df = pd.DataFrame({'a':range(20), 'b':range(100,120)})
the output:
a b
0 0 100
1 1 101
2 2 102
3 3 103
4 4 104
5 5 105
6 6 106
7 7 107
8 8 108
19 19 119