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, yearin enumerate(range(end, final_year +1), years_exp)],
columns=['end', 'id.thomas', 'years_exp'])
end id.thomas years_exp
0200713614120081361522009136163201013617420111361852012136196201313620720141362182013172149201417215
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
endid.thomas02007 13612008 13622009 13632010 13642011 13652012 13662013 13672014 13602013 17212014 172
Post a Comment for "Pandas: Inserting Rows Of Even Number Years"