Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

mark specific rows in pandas dataframe

I have a pandas dataframe like below

no.             col1             col2
 1              abc              123
 2              bcd              234
 3              cde              345

All I would like to create a new column and mark first 4 rows with number 1, rows 5 to 7 with number 2, and the remaining rows with number 3. Expected output:

no.             col1             col2           new_col
 1              abc              123               1
 2              bcd              234               1
 3              cde              345               1
 .........

I am sure it can be done fairly easily, but not able to do it, any help would be appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use cut:

df = pd.DataFrame({'col1': range(10)})
  
df['new_col'] = pd.cut(np.arange(1,len(df)+1), [-1, 4, 7, len(df)], labels=[1, 2, 3])
print (df)
   col1 new_col
0     0       1
1     1       1
2     2       1
3     3       1
4     4       2
5     5       2
6     6       2
7     7       3
8     8       3
9     9       3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading