[英]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.