如何从具有匹配索引的数据帧中减去序列

2024-09-27 07:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个DataFrame和一个Series的列。两者都有相同的DateTimeIndex。在

我想从DataFrame中每一行的值中减去Series中每一行的值

以下是我的示例数据:

dates   = pandas.date_range('20180101', periods=10)
stocks  = ['AAPL', 'GOOG', 'MSFT', 'AMZN', 'FB']
data    = numpy.random.randn(10,5)
prices  = pandas.DataFrame(index=dates, columns=stocks, data=data)
returns = prices.pct_change(1)

这给了我一个DataFrame类似于下面的

enter image description here

然后我创建我的Series,这是一篮子股票的回报

^{pr2}$

这给了我一个Series类似于下面的

enter image description here

现在我想从每只股票的回报中减去一篮子回报:

excess_ret = returns - basket

我收到以下警告:

RuntimeWarning: Cannot compare type 'Timestamp' with type 'str', sort order is
undefined for incomparable objects
  return this.join(other, how=how, return_indexers=return_indexers)

这是结果DataFrame

enter image description here

这个使用pandas-0.16.2中工作,但我现在使用的是pandas-0.22.0,现在似乎我无法从匹配的DataFrame中减去Series?在

问题:

  • 我目前正在做的这个减法操作发生了什么?在
  • 如何从DataFrame中每行的所有值中减去{}中每一行的值?在

Tags: dataframepandasdatareturntypereturnshowseries
1条回答
网友
1楼 · 发布于 2024-09-27 07:30:01

我认为需要参数为axis=0^{}来匹配DataFrame的索引Series

axis : {0, 1, 'index', 'columns'}

For Series input, axis to match Series index on

excess_ret = returns.sub(basket, axis=0)
print (excess_ret)
                AAPL      GOOG      MSFT      AMZN        FB
2018-01-01       NaN       NaN       NaN       NaN       NaN
2018-01-02 -1.833226 -0.110935  0.455586 -0.173553  1.662127
2018-01-03 -0.662713  1.737714 -1.295243  1.381853 -1.161611
2018-01-04  3.269817 -0.824819  0.377973 -0.788368 -2.034604
2018-01-05 -0.082528  1.814466  2.295359 -3.543489 -0.483808
2018-01-06  0.295950  2.978380  1.000856  1.346977 -5.622164
2018-01-07  1.988864 -2.316191  0.633370  1.043901 -1.349943
2018-01-08 -2.640122 -0.861669 -1.472634 -1.559951  6.534376
2018-01-09  8.062484 -1.712583 -2.497513 -0.807566 -3.044822
2018-01-10 -1.823915  0.370618 -0.883559  0.888679  1.448177

如果要按列匹配:

^{pr2}$

相关问题 更多 >

    热门问题