Python/for循环。。为什么我的速度这么慢?

2024-09-30 10:27:49 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我对python、jupyter环境和熊猫都是新手

我已经涉猎了一点MATLAB,这就是为什么我开始学习Jupyter、python和它的pandas库

我已经为一些数据处理建立了一个更大的数据框架(170万x9)

如果一个错误发生了150毫秒(150行),我需要检测一个错误,在MATLAB中,我可以很快地检测到这个错误~几秒钟,但是在python中,下面的循环可能需要花费一个小时+我没有耐心完成,对我来说,我的代码有问题吗

我希望输出的数据与输入的数据相同,另外还有一列,默认为0,如果TrqSpdQuadrant!=UdUq_IQRS150行的象限

PosSpdData['Fault'] = 0
pd.options.mode.chained_assignment = None # The error for rewriting a column was annoying. <- why isn't this correct?
cnt = 0
for i in range(1, len(PosSpdData['Error_IqRs'])):       
    if (PosSpdData['Error_IqRs'].values[i] == 0):  
        cnt += 1
        if cnt > 150:
            PosSpdData['Fault'][i] = 1  
        else:
            PosSpdData['Fault'][i] = 0
    else:
        cnt = 0
        PosSpdData['Fault'][i] = 0

DemandedTorque  Speed   Ud  Uq  Iq  TrqSpdQuadrant  Uq_IqRs     UdUqQuadrant    UdUq_IqRsQuadrant   Error   Error_IqRs
0   0.0     0.0     0.00000     0.00000     0.0000  0   0.000000    0   0   0   0
1   0.0     0.0     0.00000     0.00000     0.0000  0   0.000000    0   0   0   0
2   0.0     0.0     0.00000     0.00000     0.0000  0   0.000000    0   0   0   0
3   0.0     0.0     0.00000     0.00000     0.0000  0   0.000000    0   0   0   0
4   0.0     0.0     0.00000     0.00000     0.0000  0   0.000000    0   0   0   0
...     ...     ...     ...     ...     ...     ...     ...     ...     ...     ...     ...
30302   270.0   847.0   -25.40625   30.75000    461.0625    1   17.162577   1   1   0   0
30303   270.0   847.0   -25.40625   30.75000    463.1875    1   17.099954   1   1   0   0
30304   270.0   847.0   -25.40625   30.75000    463.1875    1   17.099954   1   1   0   0
30305   270.0   847.0   -25.93750   30.75000    463.1875    1   17.099954   1   1   0   0
30306   270.0   847.0   -25.93750   29.34375    463.1875    1   15.693704   1   1   0   0

Tags: 数据forif错误jupytererrorelsematlab
1条回答
网友
1楼 · 发布于 2024-09-30 10:27:49

当n>;150个连续行指向错误,否则为“False”

PosSpdData['Error_IqRs'] = PosSpdData['TrqSpdQuadrant'] != PosSpdData['UdUq_IqRsQuadrant']
data = PosSpdData['Error_IqRs'].values
PosSpdData['gr'] = np.r_[True, data[1:] != data[:-1]].cumsum()
PosSpdData['Fault'] = PosSpdData.groupby('gr')['Error_IqRs'].transform('sum') > 150

n=2_000_000行x 2列的基准测试

307 ms ± 4.57 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

相关问题 更多 >

    热门问题