减去具有共同多索引的两个数据框

时间:2020-07-01 05:29:27

标签: python pandas

有两个数据帧,其中一个非常大,如下所示:

import pandas as pd
import numpy as np
import string, random

siz = int(1e10)
random.seed(1234)
a1 = pd.Series((random.choice(string.ascii_uppercase) for _ in range(siz)), name='CatA')
a2 = pd.Series((random.choice(string.ascii_lowercase) for _ in range(siz)), name='CatB')
val1 = pd.Series(pd.Series(np.random.randint(2, high=10, size=siz), name='Value'))

df_a = pd.DataFrame([a1, a2, val1]).T.set_index(['CatA', 'CatB'])

siz = 1000
random.seed(4321)
b1 = pd.Series((random.choice(string.ascii_uppercase) for _ in range(siz)), name='CatA')
b2 = pd.Series((random.choice(string.ascii_lowercase) for _ in range(siz)), name='CatB')
val2 = pd.Series(pd.Series(np.random.randint(2, high=10, size=siz), name='Value'))

df_b = pd.DataFrame([b1, b2, val2]).T.set_index(['CatA', 'CatB'])
  • 想要快速获取两个数据帧之间基于索引的差异,同时保持df_a的Value不变。
      df_b中删除
    • df_a
    • 两个df具有相同的结构。 Value中的df_a应该保留。
    • Value中的df_b已删除。

尝试了df_a.sub(df_b.drop('Value', 1))...。

有矢量化的方法吗?

1 个答案:

答案 0 :(得分:1)

我相信您需要Index.isin,并加上~倒置的掩模:

df = df_a[~df_a.index.isin(df_b.index)]
相关问题