python - 如何加速 Pandas 数据帧上的迭代函数?

标签 python performance pandas dataframe

我对 pandas 很陌生,我有一个大约 500,000 行的 pandas 数据框,里面充满了数字。我正在使用 python 2.x,目前正在定义并调用下面所示的方法。如果系列“A”中的两个相邻值相同,则它将预测值设置为等于系列“B”中的相应值。然而,它运行速度非常慢,每秒输出大约 5 行,我想找到一种方法更快地完成相同的结果。

def myModel(df):

    A_series = df['A']
    B_series = df['B']
    seriesLength = A_series.size

    # Make a new empty column in the dataframe to hold the predicted values
    df['predicted_series'] = np.nan

    # Make a new empty column to store whether or not
    # prediction matches predicted matches B
    df['wrong_prediction'] = np.nan
    prev_B = B_series[0]
    for x in range(1, seriesLength):

        prev_A = A_series[x-1]  
        prev_B = B_series[x-1]
        #set the predicted value to equal B if A has two equal values in a row
        if A_series[x] == prev_A:
            if df['predicted_series'][x] > 0:
                 df['predicted_series'][x] = df[predicted_series'][x-1]
            else:
                 df['predicted_series'][x] = B_series[x-1]

有没有办法对其进行矢量化或使其运行得更快?在目前的情况下,预计需要几个小时。真的应该花这么长时间吗?看起来 500,000 行不应该给我的程序带来那么多问题。

最佳答案

像这样的东西应该像你描述的那样工作:

df['predicted_series'] = np.where(A_series.shift() == A_series, B_series, df['predicted_series'])

关于python - 如何加速 Pandas 数据帧上的迭代函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37215320/

相关文章:

python - 基于两列合并两个 Dataframe

python - 将 tf.Session 重写为 tf.Estimator API

python - 在 python/bash/perl 脚本中执行和读取二进制文件的输出

python - 获取所选值的索引

python - 使用数据帧生成直方图时切换轴

python - 按键(整数)对字典进行有效排序,返回排序的值列表

python - 摆脱 tkinter 中小部件周围的空白

python - 如何在找到第一个所需字符并复制其余文本后停止搜索?

c# - 对于聚合操作,LINQ 是否比 foreach 循环慢?

python - 更快的 Python 技术,用于从互为倍数的数字列表中计算三元组