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

add string based on conditional formating of a dataframe

data = {"marks":[1,2,3,4,5,6,7,8,9,10,11,12], "month":[‘jan’,’feb’,’mar’,’apr’,’may’,’jun’,’jul’,’aug’,’sep’,’oct’,’nov’,’dec’]}
df2 = pd.DataFrame(data)

Desired output:

Till now I tried below but not getting as mentioned above:

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

`

for i in df2['month']:
   if (i=='jan' or i=='feb' or i=='mar'):
        df2['q'] = '1Q'
   else:
        df2['q']='other'

`

>Solution :

Use Series.dt.quarter with convert column to datetimes and add q:

df2['new'] = 'q' + pd.to_datetime(df2['month'], format='%b').dt.quarter.astype(str)

Or use Series.map by dictionary:

d = {'jan':'q1', 'feb':'q1','mar':'q1',
     'apr':'q2','may':'q2', 'jun':'q2',
     'jul':'q3','aug':'q3', 'sep':'q3',
     'oct':'q4','nov':'q4', 'dec':'q4'}
    
df2['new'] = df2['month'].map(d)
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