在 pandas 中合并不同数量的列
merge varying number of columns in pandas
我正在尝试将数据框与各种列合并。对它们进行子集化我认为需要不同的处理方式,具体取决于它是否具有 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)
b = 'parrot'
len(b) = 6
b = 'parrot', 'mouse'
len(b) = 2
You can fix this by using lists
b = ['parrot']
and
b = ['parrot', 'mouse']
df2[[*b]] should become df2[b]
假设数据框不包含多索引列,您可以使用 .loc
to select the required columns in df2
then use pd.concat
将数据框 df1
与沿 axis=1
选择的列连接起来
pd.concat([df1, df2.loc[:, b]], axis=1)
样本运行:
# b = 'mouse'
cat dog mouse
0 0 1 1
1 1 2 2
2 2 3 3
# b = 'mouse', 'parrot'
cat dog mouse parrot
0 0 1 1 0
1 1 2 2 1
2 2 3 3 2
我正在尝试将数据框与各种列合并。对它们进行子集化我认为需要不同的处理方式,具体取决于它是否具有 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)
b = 'parrot'
len(b) = 6
b = 'parrot', 'mouse'
len(b) = 2
You can fix this by using lists
b = ['parrot']
and
b = ['parrot', 'mouse']
df2[[*b]] should become df2[b]
假设数据框不包含多索引列,您可以使用 .loc
to select the required columns in df2
then use pd.concat
将数据框 df1
与沿 axis=1
选择的列连接起来
pd.concat([df1, df2.loc[:, b]], axis=1)
样本运行:
# b = 'mouse'
cat dog mouse
0 0 1 1
1 1 2 2
2 2 3 3
# b = 'mouse', 'parrot'
cat dog mouse parrot
0 0 1 1 0
1 1 2 2 1
2 2 3 3 2