首页 > 解决方案 > 如果不逐行遍历数据框,这需要很长时间,我如何检查多行是否都满足条件?

问题描述

我想做以下事情,但显然我意识到这种迭代方法对于大型DataFrames非常慢,还有什么其他解决方案可以解决这个问题?:

for i in range(len(df)):
    for n in range(1001):
        if df["Close"][(i+n)] > df["MA"][i+n]:
            df["Strategy 1"][i] = "Buy"

我希望上面的代码做的是:

Sub in n 从 0 到 1,000到第 3 行,i 为 0,然后如果第 3 行中的条件对 0 到 1,000 范围内的每个 n 成立,那么它将继续执行第 4 行中的操作。

在此之后,它将i 取 1,然后将n 从 0 到 1,000放入第 3 行,如果条件适用于该范围内的所有 n,那么它将执行第 4 行。

在此之后,它需要i of 2,然后将n 从 0 到 1,000放入第 3 行,如果该条件适用于该范围内的所有 n,那么它将执行第 4 行。

在此之后,它将采用3 的 i,然后将n 从 0 到 1,000放入第 3 行,如果该条件适用于该范围内的所有 n,那么它将执行第 4 行。

…… _

在此之后,它将采用len(df) 的 i,然后将n 从 0 到 1,000放入第 3 行,如果该条件适用于该范围内的所有 n,那么它将执行第 4 行。

无论上面提供的代码是否符合我的预期,是否有一种更快的方法来计算非常大的多千兆字节数据帧?

标签: pythonpandasloopsiteration

解决方案


使用 .apply 函数会更快。举个一般的例子...

import pandas as pd

# only required to create the test dataframe in this example
import numpy as np

# create a dataframe for testing using the numpy import above
df = pd.DataFrame(np.random.randint(100,size=(10, )),columns=['A'])

# create a new column based on column 'A' but moving the column 'across and up'
df['NextRow'] = df['A'].shift(-1)

# create a function to do something, anything, and return that thing
def doMyThingINeedToDo(num, numNext):
#     'num' is going to be the value of whatever is in column 'A' per row 
#     as the .apply function runs below and 'numNext' is plus one.
    if num >= 50 and numNext >= 75:
        return 'Yes'
    else:
        return '...No...'

# create a new column called 'NewColumnName' based on the existing column 'A' and apply the
# function above, whatever it does, to the frame per row.
df['NewColumnName'] = df.apply(lambda row : doMyThingINeedToDo(row['A'], row['NextRow']), axis = 1)

# output the frame and notice the new column
print(df)

输出:

    A  NextRow NewColumnName
0  67     84.0           Yes
1  84     33.0      ...No...
2  33     59.0      ...No...
3  59     85.0           Yes
4  85     39.0      ...No...
5  39     81.0      ...No...
6  81     76.0           Yes
7  76     83.0           Yes
8  83     60.0      ...No...
9  60      NaN      ...No...

要点是,您可以将每行的确切内容分开并将其包含在一个函数中(可以根据需要进行调整和更新),并在需要时为框架上的所有行调用该函数。


推荐阅读