【发布时间】:2018-03-31 05:28:41
【问题描述】:
我有OG_df,即:
Symbol Order Shares
Date
2011-01-10 AAPL BUY 1500
2011-01-13 AAPL SELL 1500
2011-01-13 IBM BUY 4000
2011-01-26 GOOG BUY 1000
2011-02-02 XOM SELL 4000
2011-02-10 XOM BUY 4000
2011-03-03 GOOG SELL 1000
2011-03-03 GOOG SELL 2200
2011-05-03 IBM BUY 1500
2011-06-03 IBM SELL 3300
2011-06-10 AAPL BUY 1200
2011-08-01 GOOG BUY 55
2011-08-01 GOOG SELL 55
2011-12-20 AAPL SELL 1200
2011-12-21 AAPL BUY 20
2011-12-27 GOOG BUY 2200
2011-12-28 IBM SELL 2200
我也有df_prices,即:
AAPL IBM GOOG XOM SPY CASH
2011-01-10 340.99 143.41 614.21 72.02 123.19 1.0
2011-01-11 340.18 143.06 616.01 72.56 123.63 1.0
... ... ... ... ... ... ...
2011-11-15 387.17 186.44 616.56 77.62 124.10 1.0
2011-11-16 383.13 184.33 611.47 76.79 122.13 1.0
2011-11-17 375.80 183.45 600.87 76.41 120.19 1.0
2011-11-18 373.34 182.97 594.88 76.45 120.06 1.0
2011-11-21 367.43 179.26 580.94 75.48 117.78 1.0
2011-11-22 374.90 179.09 580.00 74.61 117.31 1.0
[245 rows x 6 columns]
我设置date_range = pd.date_range(OG_df.index.min(), OG_df.index.max()) 然后
df1 = pd.DataFrame(0, df_prices.index, columns=list(df_prices))
假设您有vals = df1.values,即:
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
...,
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]]
形状为(245, 6)
我也可以得到
cols = np.array([df1.columns.get_loc(c) for c in OG_df.Symbol])
cols 返回[0 0 1 2 3 3 2 2 1 1 0 2 2 0 0 2 1]
OG_df.Symbol 是['AAPL' 'IBM' 'GOOG' 'XOM'],所以你可以看到,OG_df 中有 4 个不同的列对应 17 个不同的行。
我也有
rows = np.arange(len(df1))
我想做类似vals[rows, cols] = some_variable 之类的事情,但会返回:
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (245,) (17,)
因为rows 是长度17 而cols 是长度245。
我想根据some_variable 填充df1 中的每个单元格(每次都不同)。
order = np.where(orders_df.Order.values == 'BUY', -1, 1)
some_variable = OG_df.Shares.values * order
len(some_variable) = 17
我该怎么做?
另外,我不想将some_variable 分配给df1 的CASH。
示例输出:
AAPL IBM GOOG XOM SPY CASH
2011-01-10 1500 0 0. 0 0. N/A
2011-01-11 0 0. 0. 0 0. N/A
2011-01-12 0 0 0 0 0 N/A
2011-01-13 -1500 4000. 0. 0. 0. N/A
【问题讨论】:
-
df[:] = vals? -
我收到
ValueError: Must have equal len keys and value when setting with an iterable -
访问您的实际数据会有很大帮助。或者可能是minimal reproducible example。
-
哦,所以您想将 OG_df.Shares 数据放在新数据框中的相应列和索引下。
-
抱歉,还不清楚...你能显示大约 5 行的预期输出吗?
标签: python pandas dataframe indexing vectorization