【发布时间】:2020-08-11 21:36:27
【问题描述】:
我正在计算处于 1 年高点的股票数量 - 1 年低点的股票数量的每日价值。我有一个名为 stocks 的 DataFrame,其中包含股票价格。
以下是正确的(我认为),但效率极低。
#get output frame
high_minus_low = pd.DataFrame(columns = ["High minus Low"], index = stocks.index)
no_highs=0
no_lows=0
#assume 260 trading days in the year
for row in range(260):
row = 260 + row
#iterate over stocks in the index
for col in range(len(stocks.columns)):
latest = stocks.iloc[row,col]
high = stocks.iloc[(row-260):row, col].max()
low = stocks.iloc[(row-260):row, col].min()
if latest >= high: no_highs = no_highs +1
if latest <= low: no_lows = no_lows + 1
#write to output
high_minus_low.iloc[row,0] = no_highs - no_lows
no_highs=0
no_lows=0
print(".\n")
谁能提出更有效的实施方案?
谁能建议一个依赖于索引(在日期中完成)而不是像我一样递增/递减坐标的实现?
提前致谢 - 我是 Python/编码初学者。
[编辑:]
输入样本:
Instrument @AMZN U:ABT U:AES @ABMD ... @MNST U:LIN @SBAC @CHTR
Field P P P P ... P P P P
Dates ...
2018-04-27 1572.620 59.56 12.31 301.7400 ... 56.19 153.23 158.95 263.3250
2018-04-30 1566.130 58.13 12.24 300.9500 ... 55.00 152.52 160.23 271.2900
2018-05-01 1582.260 58.82 12.21 310.5000 ... 55.20 153.30 157.50 279.3999
2018-05-02 1569.680 57.85 12.19 302.1399 ... 52.72 151.24 155.85 274.7800
2018-05-03 1572.075 57.93 12.30 335.5701 ... 52.31 152.84 156.16 271.3601
输出:
Dates
2018-04-27 NaN
2018-04-30 NaN
2018-05-01 NaN
2018-05-02 NaN
2018-05-03 NaN
...
2020-04-07 0
2020-04-08 3
2020-04-09 6
2020-04-10 6
2020-04-13 4
输出简单的意思是:13日个股处于高位--个股处于低位是4个。
【问题讨论】:
-
您能添加您的输入数据和预期输出吗?在没有任何上下文的情况下很难对您的代码做出正面或反面
-
感谢您的建议。问题已编辑。
-
看看 Pandas
rolling window: pandas.pydata.org/pandas-docs/stable/reference/api/… 你永远不应该按行/列迭代 DataFrame。 Pandas 具有以高效vectorized方式完成此类工作所需的所有功能。 -
谢谢。我广泛地意识到这一点,但缺乏实现这一点的知识。因此,关于 SO 的问题。
标签: python pandas for-loop indexing iteration