【问题标题】:Creating vector of datetimes for Python为 Python 创建日期时间向量
【发布时间】:2016-01-08 15:05:32
【问题描述】:

我有两个数据框df_tradedf_close,我想将它们的点积存储在ts_fund 中,但是ts_fund 是数组、数据框、向量等都没有关系。这两个数据帧将值和时间存储为datetime。例如df_trade:

2011-1-05 15 100
2011-1-20 10 200

df_close

2011-1-05 1 .5
2011-1-20 .8 .1

所以我希望ts_fund 中的结果是:

2011-1-05 65
2011-1-20 28

我尝试了以下

ts_fund = np.zeros((len(ldt_timestamps), 1))
ts_fund = pd.DataFrame(ts_fund, index=ldt_timestamps, columns='portfolio value')

 for index, row in df_trade.iterrows():
    portfolio_value = np.dot(row.values.astype(float), df_close.ix[index].values)
    ts_fund[index] = portfolio_value

但我得到了错误

TypeError: Index(...) must be called with a collection of some kind, 'portfolio value' was passed

如果我将ts_fund 设置为向量或数组而不是数据框会更容易吗?

【问题讨论】:

    标签: python python-2.7 datetime pandas


    【解决方案1】:

    这就够了吗?

    def equity(df1,df2):
        shape1 = df1.shape
        shape2 = df2.shape
        if not shape1 == shape2:
            raise Exception("df's are of different size!")
        return df1.mul(df2, axis='columns', fill_value=0).sum(axis =1)
    
    equity(df1, df2)  
    
    2011-01-05    65
    2011-01-20    28
    dtype: float64
    

    一般而言,除非绝对必要,否则应避免遍历行,并尝试利用 pandas 的矢量化操作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多