【问题标题】:dataframe merging + comparison with existence test数据框合并+与存在测试比较
【发布时间】:2017-07-07 16:50:29
【问题描述】:

我正在寻找执行以下任务:

给定 2 个 pandas DataFrame,每个都有一列但长度不同,创建一个新 DataFrame,其索引是其他 2 个 DataFrame 的并集,并拥有两列:一列指示 DataFrame 1 是否包含该特定索引的值,以及一个指示 DataFrame 2 是否包含该特定索引的值。

我有以下示例数据:

rng = pd.date_range('1/1/2017', periods=365, freq='D')
rng2 = pd.date_range('1/1/2016',periods=730, freq='D')
x1 = np.random.randn(365)
x2 = np.random.randn(730)
df1 = pd.DataFrame({'x':x1}, index=rng)
df2 = pd.DataFrame({'x':x2}, index=rng2)

我可以通过以下方式获得索引的联合:

idx = df1.index.union(df2.index)

现在,我想创建一个新的 DataFrame,df3,它的索引为 idx,并且根据上述要求,有 2 列填充了 0 和 1。

我已经探索过使用 .isin() 功能,但据我所知,这可能需要事先对 DataFrame 了解得太多,而我希望更灵活地实现这一点。

【问题讨论】:

    标签: python python-2.7 pandas numpy dataframe


    【解决方案1】:

    外部连接和notnull() 的测试实现了所需的行为。使用您的示例数据,它看起来像:

    notnull = df1.join(df2.rename(columns={'x': 'x2'}), how='outer').notnull()
    

    样本数据:

    rng1 = pd.date_range('1/2/2017', periods=4, freq='D')
    rng2 = pd.date_range('1/1/2017', periods=4, freq='D')
    x = np.random.randn(4)
    df1 = pd.DataFrame({'x': x}, index=rng1)
    df2 = pd.DataFrame({'x': x}, index=rng2)
    

    测试一下:

    notnull = df1.join(df2.rename(columns={'x': 'x2'}), how='outer').notnull()
    print(notnull)
    

    输出:

                    x     x2
    2017-01-01  False   True
    2017-01-02   True   True
    2017-01-03   True   True
    2017-01-04   True   True
    2017-01-05   True  False
    

    评论更新:

    如果你想要实际个和零而不是bool,

    ones_and_zeros= df1.join(df2.rename(columns={'x': 'x2'}), 
                                        how='outer').notnull().astype(np.uint8)
    print(ones_and_zeros)
    

    输出:

                x  x2
    2017-01-01  0   1
    2017-01-02  1   1
    2017-01-03  1   1
    2017-01-04  1   1
    2017-01-05  1   0
    

    【讨论】:

    • 不错的解决方案!我还会将转换添加到 np.uint8: df1.join(df2.rename(columns={'x': 'x2'}), how='outer').notnull().astype(np.uint8) 所以它会产生一个和零
    猜你喜欢
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 2019-06-24
    • 2023-03-08
    相关资源
    最近更新 更多