首页 > 解决方案 > 在 pandas 数据框和回填中将年扩展到月

问题描述

我有一个带有年份和一列字符串的数据框,我想将其扩展为包括月份(1-12)并回填与每年相关的字符串。

这是起始数据框:

Year Data

0   2016     YES
0   2017     NO
0   2018     NO
0   2019     YES

我也希望它看起来像:

Year  Months Climate
0   2016  1   YES
0   2016  2   YES
0   2016  3   YES
...
0   2017  1   NO
0   2017  2   NO
0   2017  3   NO
0   2017  4   NO

标签: pythonpandasdataframedatetimefill

解决方案


这是一种使用方法explode

# df is the given data in question
df.columns = ['year','flag']

# add a list for months 1-12
df['month'] = [list(range(1, 13)) for _ in range(df.shape[0])]

# convert list into rows
df = df.explode('month').reset_index(drop=True)

推荐阅读