【问题标题】:Nested for loop is time inefficient, looking for a smart alternative嵌套for循环时间效率低下,寻找智能替代方案
【发布时间】:2019-10-06 17:10:36
【问题描述】:

嵌套 for 循环的时间效率非常低。我有一些想法可以提高效率。想知道是否可以分享更好的替代方案。

我正在尝试在 python 中创建一个数据帧,从多个其他数据帧中提取值。对于少数变量/列,我可以执行简单的分配。在下面的示例中,我希望对两个数据帧中的每个单元格进行比较,并在相等时进行分配。如果它们不相等,我需要遍历第二个数据帧,直到在进行任何分配之前评估每个单元格。

"""遍历第一个数据帧的每一行,然后是第二个。这是为了控制比较列中的值 匹配正确。 """

for i in range(len(df10)):
    for j in range(len(df6)):                 # this is not an efficient way to perform this action.
        if df10.iloc[i,0] == df6.iloc[j,1]:
            df10.iloc[i,23] = df6.iloc[j,6]
            df10.iloc[i,24] = df6.iloc[j,1]
df10.sample(n=5)

【问题讨论】:

  • 如果跨数据帧进行比较,请查看merge。请发布示例数据以供我们帮助。

标签: python-3.x pandas for-loop nested


【解决方案1】:

这里是你如何做到这一点,请参阅评论中的描述。有不清楚的地方可以留言

np.random.seed(10)
df10 = pd.DataFrame(np.random.choice(5, (5,5)))

df6 = pd.DataFrame(np.random.choice(5, (4,6)))

display(df10)
display(df6)

## compare each pair of rows from 0th column of df10 and 1st column of df6
## using numpy broadcast. Which will return matrix of boolean with true at
## element i,j where values are equal
cond = df10.iloc[:,0].values[:,np.newaxis] == df6.iloc[:,1].values

## get matching index in array when the matrix is flatten 
indx = np.arange(cond.size)[cond.ravel()]

## convert flattened index to row and colum index (i,j)
## where i crossponds to row index in df10 and j crossponds to 
## row index in df6
i,j = indx//len(df6), indx%len(df6)

## set value using fancy indexing
df10.iloc[i,3] = df6.iloc[j,4].values
df10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2019-10-11
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多