【发布时间】:2017-05-20 08:01:14
【问题描述】:
我正在尝试获取我的 Pandas Dataframe 中每一行的总和:
new_df['cash_change'] = new_df.sum(axis=0)
但是我的结果不断返回NaN
我认为这可能与我将 positions 转换为 Decimal 以进行乘法运算有关:
pos_to_dec = np.array([Decimal(d) for d in security.signals['positions'].values])
我必须这样做才能将我的列相乘。但是我把它扔回去了:
cash_change[security.symbol] = cash_change[security.symbol].astype(float)
这里是完整的方法。它的目标是对每个 security 执行一些列乘法,然后在最后 sum 总和:
def get_cash_change(self):
"""
Calculate daily cash to be transacted every day. Cash change depends on
the position (either buy or sell) multiplied by the adjusted closing price
of the equity multiplied by the trade amount.
:return:
"""
cash_change = pd.DataFrame(index=self.positions.index)
try:
for security in self.market_on_close_securities:
# First convert all the positions from floating-point to decimals
pos_to_dec = np.array([Decimal(d) for d in security.signals['positions'].values])
cash_change['positions'] = pos_to_dec
cash_change['bars'] = security.bars['adj_close_price'].values
# Perform calculation for cash change
cash_change[security.symbol] = cash_change['positions'] * cash_change['bars'] * self.trade_amount
cash_change[security.symbol] = cash_change[security.symbol].astype(float)
# Clean up for next security
cash_change.drop('positions', axis=1, inplace=True)
cash_change.drop('bars', axis=1, inplace=True)
except InvalidOperation as e :
print("Invalid input : " + str(e))
# Sum each equities change in cash
new_df = cash_change.dropna()
new_df['cash_change'] = new_df.sum(axis=0)
return cash_change
我的new_df Dataframe 最终看起来像这样:
MTD ESS SIG SNA cash_change
price_date
2000-01-04 0.0 0.00 0.00 0.00 NaN
2000-01-05 0.0 0.00 0.00 0.00 NaN
2000-01-06 0.0 0.00 0.00 0.00 NaN
2000-01-07 0.0 0.00 0.00 0.00 NaN
2000-01-10 0.0 0.00 0.00 0.00 NaN
2000-01-11 0.0 0.00 0.00 0.00 NaN
2000-01-12 0.0 0.00 0.00 0.00 NaN
2000-01-13 0.0 0.00 0.00 0.00 NaN
2000-01-14 0.0 0.00 0.00 0.00 NaN
2000-01-18 0.0 0.00 0.00 0.00 NaN
2000-01-19 0.0 0.00 0.00 0.00 NaN
2000-01-20 0.0 0.00 0.00 0.00 NaN
2000-01-21 0.0 0.00 0.00 0.00 NaN
2000-01-24 0.0 1747.83 1446.71 0.00 NaN
2000-01-25 3419.0 0.00 0.00 0.00 NaN
2000-01-26 0.0 0.00 0.00 1660.38 NaN
2000-01-27 0.0 0.00 -1293.27 0.00 NaN
2000-01-28 0.0 0.00 0.00 0.00 NaN
关于我做错了什么有什么建议吗?或者可能是另一种对每一行的列求和的方法?
【问题讨论】:
-
我建议添加最小的可重现示例 - stackoverflow.com/help/mcve。这里的人通常愿意提供帮助,但我怀疑很多 SO 用户会用你当前的问题玩这个猜谜游戏
标签: python-2.7 pandas numpy dataframe nan