python - 将数据框单元格乘以矩阵值的问题
问题描述
Noob(试图学习 data_science)在数据框中有一个简单的投资组合。我想卖出每家公司的一定数量的股票,将卖出的股票数量乘以价格,然后加上现有的现金价值(15000),四舍五入到小数点后两位。简要地
new_port_df =
Name Price Starting Number_of_shares
0 MMM 10.00 50
1 AXP 20.00 100
2 AAPL 30.00 1000
3 Cash 1.00 15000
shares_sold = [[ 5.] [ 15.] [75.] [ 0.]] #(numpy.ndarray, shape (4,1))
new_port_df['Price'] =
0 10.00
1 20.00
2 30.00
3 1.00
Name: Low, dtype: float64 # pandas.core.series.Series
所以基本上现金 += 5 * 10 + 15 * 20 + 75 * 30 + 0 * 1 或 15000 + 2600 = 17600
作为中间步骤(在谷歌搜索和阅读此处的其他帖子之后),我尝试过:
cash_proceeds = np.dot(shares_sold, new_port['Price'])
ValueError: shapes (4,1) and (4,) not aligned: 1 (dim 1) != 4 (dim 0). I think I should be reshaping, but haven't had any luck.
所需的结果如下(除 17600 单元外,所有工作都正常)
updated_port_df =
Name Price Starting Number_of_shares
0 MMM 10.00 45
1 AXP 20.00 85
2 AAPL 30.00 925
3 Cash 1.00 17600 # only the 17600 not working
我能理解的简单答案优于我不能理解的复杂答案。谢谢你的帮助。
解决方案
您可以使用 pandas dot
,而不是np.dot
. 您需要一维 numpy 数组才能在系列上使用点,因此您需要转换shares_sold
为一维
shares_sold = np.array([[ 5.], [ 15.], [75.] ,[ 0.]])
shares_sold_1d = shares_sold.flatten()
cash_proceeds = new_port_df['Price'].dot(shares_sold_1d)
In [226]: print(cash_proceeds)
2600.0
为了得到你想要的输出,简单地使用.loc
赋值和减法
(new_port_df.loc[new_port_df.Name.eq('Cash'), 'Starting_Number_of_shares'] =
new_port_df.loc[new_port_df.Name.eq('Cash'), 'Starting_Number_of_shares']
+ cash_proceeds)
new_port_df['Starting_Number_of_shares'] = new_port_df['Starting_Number_of_shares'] - shares_sold_1d
Out[235]:
Name Price Starting_Number_of_shares
0 MMM 10.0 45.0
1 AXP 20.0 85.0
2 AAPL 30.0 925.0
3 Cash 1.0 17600.0
注意:如果你真的想使用np.dot
,你需要交换顺序如下
In [237]: np.dot(new_port_df['Price'], shares_sold)
Out[237]: array([2600.])
推荐阅读
- github - GitHub 存储库(如何运行)
- mongodb - MongoDB 不断崩溃——是内存不足还是 CPU 不足?
- tensorflow - Tensorflow 2.3 管道将所有数据加载到 RAM
- c - SocketCAN如何在不丢失数据的情况下尽快发送消息
- firebase - Firebase 聊天消息排序不正确
- react-native - React Native 是否有任何 SIP (VoIP) 客户端库?
- java - 如何处理java对象堆VM?
- php - Laravel 的 belongsTo 关系返回空对象
- c++ - 哪一行导致“操作员==”错误
- python - 如何在python中使用无穷大