Given a Pandas dataframe of the form
January-2021,0.294
February-2021,0.252
March-2021,0.199
...
January-2022,0.384
February-2022,0.333
March-2022,0.271
...
how do I transform it to a dataframe with 12 columns, one for each month, so it looks like
year,January,February,March,...
2021,0.294,0.252,0.199,...
2022,0.384,0.333,0.271,...
CodePudding user response:
You can do:
# `month-year` is name of date column
dates = df['month-year'].str.extract('(?P<month>\w )-(?P<year>\d )')
# `data` is name of data column
pd.crosstab(dates['year'], dates['month'], df['data'], aggfunc='first')
Output:
month February January March
year
2021 0.252 0.294 0.199
2022 0.333 0.384 0.271
CodePudding user response: