Skip to content Skip to sidebar Skip to footer

Pandas: Inserting Rows Of Even Number Years

I have the following abridged dataframe: df1 = pd.DataFrame({'end': [2007, 2013, 2014, 2013, 2014], 'id.thomas'\ : ['136', '136', '136', '172', '172'], 'years_exp': ['14', '20', '2

Solution 1:

This takes the first end and years_exp fields for a given id.thomas, and then enumerates these forward to the final year.

final_year = 2014
>>> pd.DataFrame([(year, id_, n) 
                  for id_, end, years_exp in df1.groupby('id.thomas').first().itertuples() 
                  for n, year in enumerate(range(end, final_year + 1), years_exp)], 
                 columns=['end', 'id.thomas', 'years_exp'])
    end  id.thomas  years_exp
0  2007        136         14
1  2008        136         15
2  2009        136         16
3  2010        136         17
4  2011        136         18
5  2012        136         19
6  2013        136         20
7  2014        136         21
8  2013        172         14
9  2014        172         15

Solution 2:

If years_exp doesn't yet matter, you can just build the dataframe from groupby :

df2 =pd.concat(
   [pd.DataFrame({'id.thomas':id,'end':range(s.min(),s.max()+1)})
                     for (id,s) in df1.groupby('id.thomas').end])

For

    end id.thomas
0  2007       136
1  2008       136
2  2009       136
3  2010       136
4  2011       136
5  2012       136
6  2013       136
7  2014       136
0  2013       172
1  2014       172

Post a Comment for "Pandas: Inserting Rows Of Even Number Years"