【问题标题】:merge varying number of columns in pandas合并熊猫中不同数量的列
【发布时间】: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)

【问题讨论】:

    标签: pandas merge


    【解决方案1】:

    假设数据框不包含多索引列,您可以使用 .loc 选择 df2 中所需的列,然后使用 pd.concat 连接数据框@ 987654326@ 与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
    

    【讨论】:

    • 这是一个很好的答案,谢谢!但是....索引在某些情况下确实包含重复项。好地方,我会把它添加到我的简介中
    • @siash 在这种情况下你可以使用join,检查df1.join(df2.loc[:, b])
    【解决方案2】:
    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]
    

    【讨论】:

      猜你喜欢
      • 2019-01-03
      • 1970-01-01
      • 2021-05-28
      • 2021-09-02
      • 1970-01-01
      • 2018-12-10
      • 2016-11-26
      • 1970-01-01
      • 2017-04-17
      相关资源
      最近更新 更多