Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在pandas数据框和回填中将年扩展到月_Python_Pandas_Dataframe_Datetime_Fill - Fatal编程技术网

Python 在pandas数据框和回填中将年扩展到月

Python 在pandas数据框和回填中将年扩展到月,python,pandas,dataframe,datetime,fill,Python,Pandas,Dataframe,Datetime,Fill,我有一个带有年份的数据框和一列字符串,我想扩展它以包括月份(1-12)和与每年相关联的字符串的填充 这是起始数据帧: 年度数据 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

我有一个带有年份的数据框和一列字符串,我想扩展它以包括月份(1-12)和与每年相关联的字符串的填充

这是起始数据帧:

年度数据

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
这里有一种方法:

# 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)