我想合併列Name和Depth上的兩個數據幀。左df中的深度具有單個深度列(「深度」)。然而,右邊的df有兩個深度列('top_depth'和'bottom_depth')。在Pandas中,合併兩個具有複雜多索引的dataframs
我想從左邊的df中取出每條記錄,如果可用的話,如果'深度'落在'top_depth'和'bottom_depth'之間,則從右邊的df分配一條記錄。
我已經把一些簡單的dataframes:
df1 = pd.DataFrame(np.array([
['b1', 4, 9],
['b1', 5, 61],
['b1', 15, 95],
['b1', 24, 9],
['b2', 4, 5],
['b2', 6, 6],
['b2', 44, 0]]),
columns=['name', 'depth', 'attr1'])
df2 = pd.DataFrame(np.array([
['b1', 1, 6, 66],
['b1', 14, 16, 99],
['b1', 51, 55, 9],
['b3', 0, 5, 32]]),
columns=['name', 'top_depth', 'bottom_depth', 'attr2'])
然後合併得到這個:
>>> df3
name depth top_depth bottom_depth attr1 attr2
0 b1 4.0 1.0 6.0 9.0 66.0
1 b1 5.0 1.0 6.0 61.0 66.0
2 b1 15.0 14.0 16.0 95.0 99.0
3 b1 24 NaN NaN 9 NaN
4 b2 4 NaN NaN 5 NaN
5 b2 6 NaN NaN 6 NaN
6 b2 44 NaN NaN 0 NaN
我相信我能想出一個強力的方法來此,但有有要成爲一個更好,更多熊貓的方式。
第3行(df2)中的b3發生了什麼? – 2015-04-02 23:11:26
爲什麼df2 ['top_depth'] - df2 ['bottom_depth']不一致正面或負面? – 2015-04-02 23:15:46
利亞姆你發現我的錯誤。 df2(第2行)中的第三行應該是51,55而不是55,51。我編輯了我的問題。謝謝。 df2 ['bottom_depth'] - df2 ['top_depth']應始終爲正值。 – Todd 2015-04-03 00:00:11