How to display the nth line and the last line

I need to display the nth lines and the last using pandas. I know that the nth line can be displayed using iloc

eg:

data = {"x1": [1,2,3,4,5,6,7,8,9,10], "x2": ["a","b","c","d","e","f","g","h","i","j"]}
df = pd.DataFrame(data=data)
a = df.iloc[::2]
print(a)

will display

   x1 x2
0   1  a
2   3  c
4   5  e
6   7  g
8   9  i

But I need this:

   x1 x2
0   1  a
2   3  c
4   5  e
6   7  g
8   9  i
9  10  j

how could this be achieved?

+4
source share
1 answer

Use unionindexes and select locif by default RangeIndex:

a = df.loc[df.index[::2].union([df.index[-1]])]
print(a)
   x1 x2
0   1  a
2   3  c
4   5  e
6   7  g
8   9  i
9  10  j

Detail

print(df.index[::2].union([df.index[-1]]))
Int64Index([0, 2, 4, 6, 8, 9], dtype='int64')

Another common solution:

data = {"x1": [1,2,3,4,5,6,7,8,9,10], "x2": ["a","b","c","d","e","f","g","h","i","j"]}
df = pd.DataFrame(data=data, index=[0]*10)
print (df)
   x1 x2
0   1  a
0   2  b
0   3  c
0   4  d
0   5  e
0   6  f
0   7  g
0   8  h
0   9  i
0  10  j

arr = np.arange(len(df.index))
a = df.iloc[np.union1d(arr[::2], [arr[-1]])]
print(a)
   x1 x2
0   1  a
0   3  c
0   5  e
0   7  g
0   9  i
0  10  j
+2
source

Source: https://habr.com/ru/post/1694597/


All Articles