我正在通過兩個 DataFrame 之間的合并執行左連接,左邊有一個 MultiIndex,右邊有一個索引。加入后如何保留 MultiIndex?
import pandas as pd
import numpy as np
df1 = pd.DataFrame({
'i1': np.arange(0, 100),
'i2': np.arange(0, 100),
'c': np.random.randint(0 , 10, 100)
}).set_index(['i1', 'i2'])
df2 = pd.DataFrame({
'i1': np.arange(0, 100),
'd': np.random.randint(0 , 10, 100)
}).set_index('i1')
merged = df1.merge(df2, how="left", on="i1")
merged.index # => Int64Index i1 but I want the i1, i2 index to remain
我希望這可能像重新分配舊索引一樣簡單,但看起來合并后沒有排序保證。
雖然我可以避免一起使用索引,但我需要它們。我正在使用的資料集很大,我需要在與索引合并時獲得加速。
uj5u.com熱心網友回復:
merge()
df1.merge(df2, left_index=True, right_index=True, how='left')
###
c d
i1 i2
0 0 6 2
1 1 8 6
2 2 7 7
3 3 9 6
4 4 7 5
... .. ..
95 95 5 9
96 96 9 4
97 97 8 5
98 98 4 2
99 99 1 4
join()
df1.join(df2, on='i1', how='left')
###
c d
i1 i2
0 0 6 2
1 1 8 6
2 2 7 7
3 3 9 6
4 4 7 5
... .. ..
95 95 5 9
96 96 9 4
97 97 8 5
98 98 4 2
99 99 1 4
combine_first()
df1.combine_first(df2)
###
c d
i1 i2
0 0 6 2
1 1 8 6
2 2 7 7
3 3 9 6
4 4 7 5
... .. ..
95 95 5 9
96 96 9 4
97 97 8 5
98 98 4 2
99 99 1 4
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/504393.html
