熊猫面板合并

时间:2016-06-30 17:41:26

标签: python pandas merge

用于合并面板数据的当前最佳Pandas配方是什么,例如:

sLocation = "D:\Excel-Fso.xls"
sTxtLocation = "D:\Excel-Fso.txt"
Set ObjExl = CreateObject("Excel.Application")
Set ObjWrkBk = ObjExl.Workbooks.Open(sLocation)
Set ObjWrkSht = ObjWrkBk.workSheets("Sheet1")
ObjExl.Visible = True
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSOFile = FSO.CreateTextFile (sTxtLocation)
sRowCnt = ObjWrkSht.usedRange.Rows.Count
sColCnt = ObjWrkSht.usedRange.Columns.Count
For iLoop = 1 to sRowCnt
  For jLoop = 1 to sColCnt 
    FSOFile.Write(ObjExl.Cells(iLoop,jLoop).value) & vbtab 
  Next
Next

Set ObjWrkBk = Nothing
Set ObjWrkSht = Nothing
Set ObjExl = Nothing
Set FSO = Nothing
Set FSOFile = Nothing

预期的合并是这样的:

$item1Name = 'blue';
$item2Name = 'red';
$item3Name = 'green';
$item4Name = 'orange';
$item5Name = 'yellow';

for ($x=1;$x<5;$x++){   
    $insertItem = "insert into tblInvoiceItems (invoiceItemID,invoiceID,item".$x."Name) values";
    $varName = "item".$x."Name";
    $insertItem .= "('','','".$$varName."')";
    runQuery($insertItem,$page);
}

但是,我不明白如何有效地更新原始面板p,以包含此合并。

如果print(p [:,:,'Close'])是这样的:

p = pd.Panel(np.random.randn(2,5,4),
    items=['IBM', 'AA'],
    major_axis=pd.date_range('1/1/2000', periods=5),
    minor_axis=['Open', 'High', 'Low', 'Close'])
dp = pd.Panel(np.random.randn(2,1,1),
    items=['IBM', 'Z'],
    major_axis=pd.date_range('1/8/2000', periods=1),
    minor_axis=['Close'])

然后上面的表合并将如下所示:

p[:,:,'Close'].merge(dp[:,:,'Close'],
    how='outer',
    on=list(set(p.items) & set(dp.items)),
    left_index=True,
    right_index=True)

谢谢。

1 个答案:

答案 0 :(得分:1)

我会转换为数据帧,combine_first,然后再转回

new = p.to_frame().combine_first(dp.to_frame()).to_panel()

print new[:,:,'Close']

                  AA       IBM        Z
major                                  
2000-01-01  1.348884  0.472272      NaN
2000-01-02  1.599357 -0.228739      NaN
2000-01-03  2.041504 -0.325773      NaN
2000-01-04  0.348960 -0.451274      NaN
2000-01-05 -1.902347  0.146647      NaN
2000-01-08       NaN -0.240884  0.39855
相关问题