Home > OS >  Counting each day in a dataframe
Counting each day in a dataframe

Time:11-18

Say I have a dataframe 'df':

enter image description here

I would like to add an additional column named 'Day No' which adds a count to each day. Desired output below:

enter image description here

This wont reset at the end of each month, the count will just continue. For example at the end of the year it will read 365 for all the 1 hour entries in the last day of the year. The dtype of column 'Datetime' is datetime64[ns].

Any help greatly appreciated, Thanks.

CodePudding user response:

here is one way to do it

# convert to datetime and extract dayofyear

df['Day No']= pd.to_datetime(df['DateTime'], dayfirst=True).dt.dayofyear

PS: if you had shared df constructor or as text, i would have been able to share the result

CodePudding user response:

You can map the result of enumerated unique values:

reversed_dict = dict(enumerate(df['DateTime'].unique(), 1))

df['Day No'] = df['DateTime'].map({v:k for k,v in reversed_dict.items()})
  • Related