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
CodePudding user response:
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)
CodePudding user response:
You can use numpy:
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