使用嵌套循环的熊猫分配导致内存错误 - python

我正在使用熊猫,并尝试使用嵌套循环进行分配。我遍历一个数据框,然后运行一个满足特定条件的距离函数。我面临两个问题:

SettingWithCopyWarning:
试图在DataFrame的切片副本上设置一个值
内存错误。它不适用于大型数据集。我最终不得不终止该过程。

我应该如何更改解决方案以确保它可以扩展到具有60,000行的更大数据集?

for i, row in df.iterrows():
    listy = 0
    school = []
    if row['LS_Type'] == 'Primary (1-4)':
        a = row['Northing']
        b = row['Easting']
        LS_ID = row['LS_ID']
        for j, row2 in df.iterrows():
            if row2['LS_Type'] == 'Primary (1-8)':
                dist_km = distance(a,b, df.Northing[j], df.Easting[j])
                if (listy == 0):
                    listy = dist_km
                    school.append([df.LS_Name[j], df.LS_ID[j]])
                else:
                    if dist_km < listy:
                        listy = dist_km
                        school[0] = [df.LS_Name[j], int(df.LS_ID[j])]
        df['dist_up_prim'][i] = listy
        df["closest_up_prim"][i] = school[0]

    else:
        df['dist_up_prim'][i] = 0

python参考方案

double for循环在这里杀死了您。看看是否可以将其分解为两个单独的应用步骤。

这是一个使用df.apply()partial进行嵌套的for循环的玩具示例:

import math
import pandas as pd
from functools import partial

df = pd.DataFrame.from_dict({'A': [1, 2, 3, 4, 5, 6, 7, 8],
                             'B': [1, 2, 3, 4, 5, 6, 7, 8]})

def myOtherFunc(row):
    if row['A'] <= 4:

        return row['B']*row['A']

def myFunc(the_df, row):
    if row['A'] <= 2:
        other_B = the_df.apply(myOtherFunc, axis=1)
        return other_B.mean()
    return pd.np.NaN

apply_myFunc_on_df = partial(myFunc, df)

df.apply(apply_myFunc_on_df, axis=1)

您可以用这种形式重写代码,这将更快。

我不明白为什么sum(df ['series'])!= df ['series']。sum() - python

我正在汇总一系列值,但是根据我的操作方式,我会得到不同的结果。我尝试过的两种方法是:sum(df['series']) df['series'].sum() 他们为什么会返回不同的值?示例代码。s = pd.Series([ 0.428229 , -0.948957 , -0.110125 , 0.791305 , 0…

Python pytz时区函数返回的时区为9分钟 - python

由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

Python:同时在for循环中添加到列表列表 - python

我想用for循环外的0索引值创建一个新列表,然后使用for循环添加到相同的列表。我的玩具示例是:import random data = ['t1', 't2', 't3'] masterlist = [['col1', 'animal1', 'an…

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…