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)

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


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


>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 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)

Leave a ReplyCancel reply