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

时间:2018-06-30 19:15:59

标签: python pandas dataframe

我有一个DataFrame,其中有许多列,还有一个Series。两者具有相同的DateTimeIndex

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

这是我的示例数据:

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,这是一篮子股票的回报

basket = returns.mean(axis=1)

这给了我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,看来我无法从{{ 1}}现在匹配Series

问题:

  • 我当前正在执行的减法操作中发生了什么?
  • 如何从DataFrame中每一行的所有值中减去Indexes中每一行的值?

1 个答案:

答案 0 :(得分:1)

我认为需要sub和参数axis=0来匹配DataFrameSeries的索引:

  

轴:{0,1,'索引','列'}

     

对于“系列”输入,轴与“系列”索引相匹配

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

如果要按列匹配:

a = returns.mean(axis=0)
print (a)
AAPL    0.088224
GOOG   -1.301244
MSFT   -2.436290
AMZN   -1.009339
FB     -0.102484
dtype: float64

excess_ret = returns.sub(a, axis=1)
print (excess_ret)
                AAPL      GOOG       MSFT      AMZN        FB
2018-01-01       NaN       NaN        NaN       NaN       NaN
2018-01-02 -1.353102  1.441870   5.759181  0.421661 -0.608508
2018-01-03 -0.434575 -0.969659   0.665239  0.823154  4.917633
2018-01-04  8.771575 -2.722012   0.409977 -2.113780 -1.164615
2018-01-05 -0.220083  0.213942   1.329937 -0.372537  0.037217
2018-01-06 -0.633686  6.371478 -14.157027 -0.831583  1.226992
2018-01-07 -2.363521  0.130848   1.743317 -1.381718 -1.929583
2018-01-08 -3.062185 -6.431137   0.438800  0.956752 -1.641623
2018-01-09 -0.450300  2.093572   2.965726 -0.617335  1.042234
2018-01-10 -0.254123 -0.128903   0.844849  3.115386 -1.879747