PaulCoder
PaulCoder

Reputation: 27

Is there a way to pivot a datetime column in a dataframe into columns with the months with Python?

I have the next problem with a dataframe

Product Arrive Time
00001 2021-1-25
00002 2021-2-25
00003 2021-3-25
00001 2021-4-25
00002 2021-4-25
00003 2021-3-10

Like this I have a lot of entries. It is possible to pivot o to split the column arrive Time into months, to have something like this?

Product January February March April
00001 Yes na na yes
00002 na yes na yes
00003 na na yes na

Upvotes: 0

Views: 47

Answers (1)

Corralien
Corralien

Reputation: 120439

Use crosstab:

>>> pd.crosstab(df['Product'], df['Arrive Time'].dt.strftime('%B')) \
      .astype(bool).replace({True: 'Yes', False: 'na'})

Arrive Time April February January March
Product                                 
1             Yes       na     Yes    na
2             Yes      Yes      na    na
3              na       na      na   Yes

Upvotes: 1

Related Questions