I need to add a new column in a python data frame that has the dates of January in a column. Each date is repeated 24 times in the column without any intervention. The total number of entries will thus be 31*24 = 744 entries. Can you please help me code this part ?
1 Answer
This turns out to be fairly simple! There is a handy method called repeat
on a datetime index. Here are the steps:
import pandas as pd
Define a date range, supplying start and end
jan = pd.date_range(start="1-Jan-2018", end="31-Jan-2018") # could specify any year
Now provide how many times you want to repeat each date and create the repeated column
num_repeats = 24
repeated_jans = jan.repeat(num_repeats)
Let's create the random dummy dataframe as a base
total_dates = num_repeats * len(jan) # 24 x 31 = 744
df = pd.DataFrame(np.random.randint(0, 10, total_dates))
This is how we add a column - the name of the column can be anything
df['repeated_jans_lalala'] = repeated_jans
Have a look at some dates:
print(df.iloc[[0, 24, 48, 71, 72]]) # multiples of 24...we can see one repeated date
0 repeated_jans_lalala
0 7 2018-01-01
24 4 2018-01-02
48 3 2018-01-03
71 6 2018-01-03
72 3 2018-01-04
If try adding the column to a dataframe with a different number of rows, we get an error:
df_error = pd.DataFrame(np.random.randint(0, 10, 743)) # require 744!
#df_error['repeated_jans'] = repeated_jans # raises ValueError
If you want to change the way the dates look, you can use the strftime
method on the dates
jans_fancy = jans.strftime('%d-%B-%y')
df['fancy_jans'] = jans_fancy
df.head()
0 repeated_jans_lalal fancy_jans
0 7 2018-01-01 01-January-18
1 2 2018-01-01 01-January-18
2 8 2018-01-01 01-January-18
3 9 2018-01-01 01-January-18
4 7 2018-01-01 01-January-18
If you don't want to show the actual year, just leave out the %y
part!