pandas :插入偶数年的行 [英] Pandas: inserting rows of even number years

查看:142
本文介绍了 pandas :插入偶数年的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下删节数据框

df1 = pd.DataFrame({'end': [2007, 2013, 2014, 2013, 2014], 'id.thomas'\
: ['136', '136', '136', '172', '172'], 'years_exp': ['14', '20', '21', \
'14', '15']}, index=[2,3,4,5,6])

    end     id.thomas   years_exp
2   2007    136         14
3   2013    136         20
4   2014    136         21
5   2013    172         14
6   2014    172         15

其中 end 代表年份。我想将结束 years_exp 列扩展到缺少年份的帐户帐户:

where end is representative of years. I would like to expand the endand years_expcolumn to account account for the missing years:

    end     id.thomas   years_exp
2   2007    136         14
3   2008    136         15
4   2009    136         16
5   2010    136         17
6   2011    136         18
7   2012    136         19
8   2013    136         20
9   2014    136         21
10  2013    172         14
11  2014    172         15 

我一直在研究这个问题大约20个小时,试图'设计'修复。有没有人知道一个简单的Python / Pandas工具/方法来完成这个任务?

I have been working on this for about 20 hours, trying to 'engineer' a fix. Does anyone know of a simple Python/Pandas tool/method for accomplishing this task?

推荐答案

这需要第一个结束 years_exp 给定 id.thomas 的字段,然后枚举这些转发到最后一年。

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

这篇关于 pandas :插入偶数年的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆