比较两个数组中的元素,并使用python当一个值大于另一个值时返回True

问题描述:

我正在尝试在python中编写一个for循环,该循环将一个数组px中的每个ith元素与另一个数组py中的ith元素进行比较.如果px中的元素大于或等于py的元素,那么我要注意该值为True或1.

I'm trying to write a for loop in python that compares each ith element in one array px to the ith element in another array py. If the element in px is greater than or equal to that of py than I want to note that value as True or 1.

这是一些代码.

import pandas as pd
import random

px = np.random.normal(loc=0, scale=1, size=1000)
py = np.random.normal(loc=0, scale=1, size=1000)

for x, y in zip(px, py):
    print("{}% {}".format(x, y))
    if px[i] >= py[i]:
       px['status'] = True
    if px[i] < py[i]:
       px['status'] = False

最终数据框应如下所示:

The final dataframe should look something like this:

px                py                status
-2.24239571e-01   -1.83834445e+00   False
1.20102447e+00    5.01755172e-03    False    
8.82060986e-02    -2.55639665e-02   True

我知道我的for循环有一些问题.

I know I have some problems with my for loop.

如果要提高速度,则不应遍历数组.相反,可以使用df['status'] = px >= py在矢量化操作中进行比较.从您的问题尚不清楚数据是否已存在于数据框中,因此从头开始:

You should not be iterating through arrays if you want speed. Instead, the comparison can be done in a vectorized operation using df['status'] = px >= py. It's not clear from your question if the data is already in a Dataframe, so from scratch:

import numpy as np
import pandas as pd
px = np.random.normal(loc=0, scale=1, size=1000)
py = np.random.normal(loc=0, scale=1, size=1000)

df = pd.DataFrame({'px': px, 'py': py, 'status': px >= py})
print(df.head())