2017-09-06 85 views
1

我有2個dataframes我想結合,但它們不共享的索引重複添加爲行列數據幀Python 2.7版熊貓0.17.1

第一個具有以下結構:

date mail_volume 2011-01-01 100 2011-02-01 150 2011-03-01 125 ...

第二使用分位數函數創建:

df.quantile([.25,.50,.75])

,並具有結構:

mail_volume 0.25 110 0.50 120 0.75 130

我想創建第三個數據幀具有以下結構,其中位數查詢結果與原結果一起重複每月:

date mail_volume metric_type 2011-01-01 100 result 2011-01-01 110 .25 2011-01-01 120 .50 2011-01-01 130 .75 2011-02-01 150 result 2011-02-01 110 .25 2011-02-01 120 .50 2011-02-01 130 .75

我有搜索追加和插入行到一個數據框,但這些都不能解決我的問題,因爲需要重複日期並添加metric_type列。

由於提前, 埃裏克

+0

我們可以加入使用mail_volume兩個數據幀 – Shijo

回答

0

讓我們做一個笛卡爾合併和CONCAT與原數據幀:

pd.concat([df.assign(metric_type='result'), 
      df.assign(key=1).merge(df2.reset_index().assign(key=1), on='key', suffixes=('_x',''))[['date','mail_volume','index']].rename(columns={'index':'metric_type'})])\ 
    .sort_values(by='date') 

輸出:

 date mail_volume metric_type 
0 2011-01-01   100  result 
0 2011-01-01   110  0.25 
1 2011-01-01   120   0.5 
2 2011-01-01   130  0.75 
1 2011-02-01   150  result 
3 2011-02-01   110  0.25 
4 2011-02-01   120   0.5 
5 2011-02-01   130  0.75 
2 2011-03-01   125  result 
6 2011-03-01   110  0.25 
7 2011-03-01   120   0.5 
8 2011-03-01   130  0.75