我有一个数据框列,其中包含格式如下所示的值:
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/