[英]Pandas dataframe add 2 dataframes
I need to be able to add the values of two dataframes with the same structure together and form a new dataframe as a result. 我需要能够将两个具有相同结构的数据框的值相加在一起,从而形成一个新的数据框。
eg DF1 + DF2 = DF3 例如DF1 + DF2 = DF3
DF1
+------------+----+----+----+
| date | A | B | C |
+------------+----+----+----+
| 2017-01-01 | 24 | 15 | 4 |
| 2017-01-02 | 31 | 10 | 12 |
| 2017-01-03 | 9 | 47 | 3 |
+------------+----+----+----+
DF2
+------------+----+----+----+
| date | A | B | C |
+------------+----+----+----+
| 2017-01-01 | 4 | 12 | 63 |
| 2017-01-02 | 23 | 0 | 31 |
| 2017-01-03 | 61 | 22 | 90 |
+------------+----+----+----+
DF3
+------------+----+----+----+
| date | A | B | C |
+------------+----+----+----+
| 2017-01-01 | 28 | 27 | 67 |
| 2017-01-02 | 64 | 10 | 43 |
| 2017-01-03 | 70 | 69 | 93 |
+------------+----+----+----+
I've been trying to work out how to do this but i'm getting a TypeError 我一直在尝试找出方法,但遇到TypeError
TypeError: unsupported operand type(s) for +: 'datetime.date' and 'datetime.date'
when trying to do: 尝试做时:
df3 = df1.add(df2, fill_value=0)
I'm sure i'm missing something simple as it appears to be trying to add the first columns (which is a date and the column I want to match on to add together the values for all other columns) but any help would be greatly appreciated. 我确定我缺少一些简单的东西,因为它似乎试图添加第一列(这是一个日期和我想匹配的列,以将所有其他列的值加在一起),但任何帮助都会很大赞赏。
You want the date
columns to be indices, not normal columns: 您希望
date
列为索引,而不是普通列:
df3 = df1.set_index('date').add(df2.set_index('date'), fill_value=0).reset_index()
You use set_index()
so that the date columns becomes indices. 您使用
set_index()
以便日期列成为索引。 If you don't want the final dataframe to be date-indexed, you can use reset_index()
at the end as @MaxU suggests. 如果您不希望对最终数据帧进行日期索引,则可以按照@MaxU的建议在末尾使用
reset_index()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.