Karen Galstyan
Karen Galstyan

Reputation: 149

How to display nth-row and last row

I need to display nth rows and last one using pandas. I know that nth-rows could be displayed by using iloc

for example:

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 it to be:

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

how it could be achieved?

Upvotes: 4

Views: 603

Answers (1)

jezrael
jezrael

Reputation: 863801

Use union of indices and select by loc if 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 more general 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

Upvotes: 2

Related Questions