How to label the last three rows of a table as "a" using pandas in python

Viewed 30

How to label the last two rows of a table as "test" and the other rows as "-" using pandas in python?

Example:

+-------+
|sample |
+-------+
|    abc|
|    bcd|
|    cde|
|    edc|
+-------+

Become:

+-------++-------+
|sample ||result |
+-------++-------+
|    abc||      -|
|    bcd||      -|
|    cde||   test|
|    edc||   test|
+-------++-------+

Thank you

2 Answers

If there are 2 or more rows in DataFrame use:

df['result'] = ['-'] * (len(df.index) - 2) + ['test'] * 2

print (df)
  sample result
0    abc      -
1    bcd      -
2    cde   test
3    edc   test

If possible one row DataFrame:

df['result'] = ['-'] * (len(df.index) - 2) + ['test'] * min(len(df.index), 2)

You can use :

import numpy as np

N = 2
df['result'] = np.where(np.arange(len(df))<len(df)-N, '-', 'test')

output:

  sample result
0    abc      -
1    bcd      -
2    cde   test
3    edc   test
Related