【发布时间】:2017-03-24 13:00:57
【问题描述】:
我已经编写了一些代码,它使用字典将 DataFrame 中的值替换为另一个框架中的值,并且它正在工作,但我在一些大文件上使用它,其中字典可能会变得很长。几千双。然后,当我使用此代码时,它的运行速度非常慢,并且在某些情况下它也出现了内存不足的情况。
我有点相信我的方法远非最佳,必须有一些更快的方法来做到这一点。我创建了一个简单的示例,可以满足我的需求,但是对于大量数据来说这很慢。希望有人有更简单的方法来做到这一点。
import pandas as pd
#Frame with data where I want to replace the 'id' with the name from df2
df1 = pd.DataFrame({'id' : [1, 2, 3, 4, 5, 3, 5, 9], 'values' : [12, 32, 42, 51, 23, 14, 111, 134]})
#Frame containing names linked to ids
df2 = pd.DataFrame({'id' : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'name' : ['id1', 'id2', 'id3', 'id4', 'id5', 'id6', 'id7', 'id8', 'id9', 'id10']})
#My current "slow" way of doing this.
#Starts by creating a dictionary from df2
#Need to create dictionaries from the domain and banners tables to link ids
df2_dict = dict(zip(df2['id'], df2['name']))
#and then uses the dict to replace the ids with name in df1
df1.replace({'id' : df2_dict}, inplace=True)
【问题讨论】:
标签: python-3.x pandas dictionary replace