我希望执行以下任务:
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/