给定形式为的Pandas Dataframe
January-2021,0.294
February-2021,0.252
March-2021,0.199
...
January-2022,0.384
February-2022,0.333
March-2022,0.271
...
如何将其转换为具有12列(每个月一列)的 Dataframe ,使其看起来
year,January,February,March,...
2021,0.294,0.252,0.199,...
2022,0.384,0.333,0.271,...
3条答案
按热度按时间esbemjvw1#
您可以:
输出:
6jjcrrmo2#
您可以先使用
str.split
,然后再使用pd.pivot
。输出:
ubof19bj3#
我将使用
pivot
来获得所需的输出。prepare dataframe
data = [('January-2021',0.294), ('February-2021',0.252), ('March-2021',0.199),
('January-2022',0.384), ('February-2022',0.333), ('March-2022',0.271) ]
df = pd.DataFrame(data, columns=['date', 'val'])
extract month and year
df['month'] = df['date'].apply(lambda x: x.split('-')[0])
df['year'] = df['date'].apply(lambda x: x.split('-')[1])
df.drop(['date'], axis=1, inplace=True)
pivoting the dataframe
df = df.pivot(index='year', columns='month')
rename the columns
df.columns = [c[1] for c in df.columns]
df = df.reset_index()
最后,您将得到以下结果: