anewone
anewone

Reputation: 35

python - add range of time as column name

I want to add a range of time between 2021-05-01 until the current month, let say 2021-10-01, as columns to my dataframe as below:

Category
A
B
C

The result should look like this

Category   2021-05-01   2021-06-01   2021-07-01   2021-08-01   2021-09-01   2021-10-01
A
B
C

Can anyone help?

Upvotes: 0

Views: 121

Answers (1)

jezrael
jezrael

Reputation: 863031

Use date_range for new datetimes, if necessary dates add DatetimeIndex.date:

r = pd.date_range('2021-05-01', pd.to_datetime('now'), freq='MS').date

df = df.join(pd.DataFrame(columns=r, index=df.index))

Or:

r = pd.date_range('2021-05-01', pd.to_datetime('now'), freq='MS').date

for c in r:
    df[c] = np.nan

Upvotes: 1

Related Questions