添加两个具有不同索引的pandas数据帧

时间:2018-04-26 14:20:06

标签: python pandas series

我有两个数据帧,每个数据帧都有很多列和行。每行中的元素是相同的,但它们的索引是不同的。我想添加两个数据帧的一列的元素。

作为一个基本示例,请考虑以下两个系列:

Sr1 = pd.Series([1,2,3,4], index = [0, 1, 2, 3])
Sr2 = pd.Series([3,4,-3,6], index = [1, 2, 3, 4])

假设每行包含相同的元素,仅在不同的索引中。我想添加两列,最后得到一个包含[4,6,0,10]的新列。相反,由于索引,我得到[nan, 5, 7, 1]

有没有一种简单的方法可以在不改变指数的情况下解决这个问题?

我希望输出为系列。

4 个答案:

答案 0 :(得分:2)

您可以使用reset_index(drop=True)

Sr1 = pd.Series([1,2,3,4], index = [0, 1, 2, 3])
Sr2 = pd.Series([3,4,-3,6], index = [1, 2, 3, 4])

Sr1 + Sr2.reset_index(drop=True)

0     4
1     6
2     0
3    10
dtype: int64

此外,

pd.Series(Sr1.values + Sr2.values, index=Sr1.index)

答案 1 :(得分:1)

一种方法是在一个或多个系列中使用reset_index

Sr1 = pd.Series([1,2,3,4], index = [0, 1, 2, 3])
Sr2 = pd.Series([3,4,-3,6], index = [1, 2, 3, 4])

res = Sr1 + Sr2.reset_index(drop=True)

0     4
1     6
2     0
3    10
dtype: int64

答案 2 :(得分:0)

使用zip

<强>实施例

import pandas as pd

Sr1 = pd.Series([1,2,3,4], index = [0, 1, 2, 3])
Sr2 = pd.Series([3,4,-3,6], index = [1, 2, 3, 4])

sr3 = [sum(i) for i in zip(Sr1, Sr2)]
print(sr3)

<强>输出:

[4, 6, 0, 10]

答案 3 :(得分:0)

你可以使用.values,这会给你一个numpy表示,然后你可以像这样添加它们:

Sr1.values + Sr2.values
相关问题