添加/减去具有不同列标签的数据框 [英] Add/subtract dataframes with different column labels

查看:63
本文介绍了添加/减去具有不同列标签的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加/减去具有不同列标签的两个数据框.是否可以在不重命名列以使其对齐的情况下执行此操作?我想保留原始标签.

I'm trying to add/subtract two dataframes with different column labels. Is it possible to do this without renaming the columns to align them? I would like to keep the original labels.

推荐答案

考虑数据框AB

A = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
B = pd.DataFrame([[1, 2], [3, 4]], ['c', 'd'], ['C', 'D'])


A

B

将它们加在一起,我们一团糟.

Add them together and we have a mess.

A + B

添加其基础数组

A.values + B.values

array([[2, 4],
       [6, 8]])

这更接近我们想要的.

要获得所需的内容,您需要确定哪个数据框具有所需的列和索引,并将另一个的值添加到所选的数据框.假设我选择保留A的索引.

To get what you asked for, you need to decide which dataframe has the columns and index you want and add the values of the other to the dataframe you chose. Let's say I choose to keep A's indices.

A + B.values

那应该做到的!

这篇关于添加/减去具有不同列标签的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆