[英]How to convert start and end dates of rows into monthly chunks using pandas?
[英]How to extract a DataFrame using start and end dates with Pandas
我们如何使用开始日期和结束日期提取DataFrame
并实现此输出?
输入
id start end
1 2009 2014
2 2010 2012
产量
id data
1 2009
1 2010
1 2011
1 2012
1 2013
1 2014
2 2010
2 2011
2 2012
创建由['id']
分组的年份之间的日期枚举。 索引的其他重新格式化是可选的
import numpy as np
import pandas as pd
melted = df.groupby('id').apply(lambda x:pd.Series(np.arange(x['start'],x['end']+1)))
melted.index = melted.index.droplevel(1)
id
1 2009
1 2010
1 2011
1 2012
1 2013
1 2014
2 2010
2 2011
2 2012
采用:
df1 = (pd.concat([pd.Series(r.id,np.arange(r.start, r.end + 1)) for r in df.itertuples()])
.reset_index())
df1.columns = ['data','id']
df1 = df1[['id','data']]
print (df1)
id data
0 1 2009
1 1 2010
2 1 2011
3 1 2012
4 1 2013
5 1 2014
6 2 2010
7 2 2011
8 2 2012
有点难以理解,我认为这应该比应用稍快
通过使用reindex
并repeat
df.reindex(df.index.repeat(df['end']-df['start']+1)).assign(year=lambda x : x['start']+x.groupby('id').cumcount())
Out[453]:
id start end year
0 1 2009 2014 2009
0 1 2009 2014 2010
0 1 2009 2014 2011
0 1 2009 2014 2012
0 1 2009 2014 2013
0 1 2009 2014 2014
1 2 2010 2012 2010
1 2 2010 2012 2011
1 2 2010 2012 2012
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.