更新熊猫系列每行中某些字典键的值

时间:2019-07-24 07:38:28

标签: python-3.x pandas

请考虑以下具有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

0 个答案:

没有答案