请考虑以下具有fruits
类型行的系列dict
的数据框。目的是用每行中的“是”更新inspected
键,并用quality
的相应行值更新quality_after_inspection
键值。我已经使用enumerate
实现了这一目标,但我正在寻找一种更像熊猫的解决方案,该解决方案更加紧凑并且也许也更快,因为数据集非常大(50,000,000行)。在分析我的代码时,发现此for循环花费的时间最长。
In [2]: df = pd.DataFrame({'fruits':[{'apple':2, 'inspected': 'no', 'quality':''}, {'oranges':5, 'inspected':'no', 'qua
...: lity':''}], 'quality_after_inspection':['bad', 'good']})
In [5]: df.head()
Out[5]:
fruits quality_after_inspection
0 {'apple': 2, 'inspected': 'no', 'quality': ''} bad
1 {'oranges': 5, 'inspected': 'no', 'quality': ''} good
In [6]: for index,elem in enumerate(df.fruits):
...: elem['inspected'] = 'yes'
...: elem['quality'] = df.loc[index, 'quality_after_inspection']
...:
In [7]: df.head()
Out[7]:
fruits quality_after_inspection
0 {'apple': 2, 'inspected': 'yes', 'quality': 'bad'} bad
1 {'oranges': 5, 'inspected': 'yes', 'quality': 'good'} good