python - 数据框合并+与存在性测试比较

标签 python python-2.7 pandas numpy dataframe

我希望执行以下任务:

Given 2 pandas DataFrames, each with one column but of different length, create a new DataFrame whose index is the union of the 2 other DataFrames and possesses two columns: one indicating whether DataFrame 1 contained a value for that particular index, and one indicating whether DataFrame 2 contained a value for that particular index.

我有以下示例数据:

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,并根据上述要求用 0 和 1 填充了 2 列。

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

最佳答案

外连接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

评论更新:

如果您想要实际的 1 和 0 而不是 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

关于python - 数据框合并+与存在性测试比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42310161/

相关文章:

python - 使用 python 创建一个中文文件夹

python - Tkinter 在 Mac 上的 Tk() 上不断崩溃

python - 如何在Python中使用re.sub()在一组表达式之前和之后添加空格?

python - 用 re.sub 替换命名的捕获组

python - 如何防止引发 asyncio.TimeoutError 并继续循环

python - 如何自定义 QListWidget 背景颜色(而不是 QListWidgetItem)

python-2.7 - Scrapy Crawl Spider 不跟踪链接

python-3.x - 如何将数据框中的多列组合为 Pandas 日期时间格式

python - 用之前的非缺失值填充缺失的 pandas 数据,按键分组

python - 如何对一列的值求和并将它们按另一列分组