【发布时间】:2022-01-06 12:15:35
【问题描述】:
我正在尝试将数据框与各种列合并。我认为对它们进行子集化需要不同的处理,具体取决于它是否具有 1 列或 >1 列,因此我尝试使用 if 语句,但它不起作用,我不知道为什么。任何提示都会非常感谢
编辑 - 索引包含重复值,所以不能使用 pd.concat - 我想保留这些
df1 = pd.DataFrame(data={'cat':[0,2,1], 'dog':[1,2,3]}).set_index([pd.Index([2, 2, 4])])
df2 = pd.DataFrame(data={'mouse':[1,2,3],'parrot':[0,1,2],'elephant':[0,1,2]}).set_index([pd.Index([1, 2, 4])])
# b can be varying but for this instance lets use two columns
# b = 'parrot'
b = 'parrot', 'mouse'
if len(b) > 0:
if len(b) > 1:
out = df1.merge(df2[[*b]],left_index=True, right_index=True)
else:
out = df1.merge(df2[b],left_index=True, right_index=True)
【问题讨论】: