python - 尝试在每个数据帧列条目中搜索与 'Id' 对应的值时出现内存错误

标签 python pandas dataframe out-of-memory

我有一个数据框列,其中包含格式如下所示的值:

df = pd.DataFrame(data={'c':[{'name': 'Paramount Pictures', 'id': 4}, {'name': 'United Artists', 'id': 60}, {'name': 'Metro-Goldwyn-Mayer (MGM)', 'id': 8411}]})

df
                  c
0            {'name': 'Paramount Pictures', 'id': 4}
1               {'name': 'United Artists', 'id': 60}
2  {'name': 'Metro-Goldwyn-Mayer (MGM)', 'id': 8411}

我想提取与Id对应的所有值,例如4,60,8411。我为其编写了以下代码:

def FindIdInColumn(column,callBack,fieldName):
    for i in range(0,len(column)):
        collectionJson = column[i]
        if type(collectionJson) !=str or collectionJson == '':
            continue
        idIndex = 0
        idIndex = collectionJson.find(fieldName,idIndex,len(collectionJson))
        while idIndex != -1:
            idStr = ''
            j = idIndex+5
            while j<len(collectionJson) and collectionJson[j]!=',':
                if not(collectionJson[j].isspace()) and collectionJson[j].isnumeric():
                    idStr = idStr + collectionJson[j]
                j=j+1
            callBack(i,idStr)
            idIndex = idIndex+2
            idIndex = collectionJson.find(fieldName,idIndex,len(collectionJson))

这里column是数据框列,fieldName是'Id',callback是提取Id值后要调用的函数。
该函数消耗大量 RAM,因为我在 7 列上运行该函数。有没有办法优化这个函数以使用les内存。

最佳答案

这是我所做的:

df = pd.DataFrame(data={'c':[{'name': 'Paramount Pictures', 'id': 4}, 
                             {'name': 'United Artists', 'id': 60}, 
                             {'name': 'Metro-Goldwyn-Mayer (MGM)', 'id': 8411}]})

df['id'] = df.apply(lambda r: dict(r['c'])['id'], axis=1)

df['id'].tolist()
[4, 60, 8411]

关于python - 尝试在每个数据帧列条目中搜索与 'Id' 对应的值时出现内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59289580/

相关文章:

python - 我如何通过 Pandas 获得号码

python - 获取两个日期 Pandas 之间的周数

Python:如何将数据框中的 3 列作为函数中的 3 个单独参数传递并遍历列值

python获取linux文件不可变属性

python - 按数据框中的对象属性分组

r - 如何在 R/Shiny 中构建响应式(Reactive)数据框?

Python 具有条件的数据帧的聚合总和

python - 如何使用 yscale ('log' 拟合曲线) - Python

python - dtype=datetime64[ns] 和日期之间的比较无效

python - 无法在 flask 中创建 key ;返回 “name ' session '未定义”