首页 > 解决方案 > 处理pandas groupby中的项目很慢?我们应该使用哈希图吗?

问题描述

我们有一个选民登记数据的熊猫数据框。我们所做的如下:

  1. 按地址对选民进行分组——这会在数据框中产生组,然后我们可以处理这些组。
  2. 鉴于这些组,我们现在遍历它们中的每一个,其中每个组有两个不同性别的人,我们可能将他们归类为一对。
  3. 如果我们有一对夫妇,我们会进一步将他们分成具有相同或不同政党隶属关系的人。换句话说,民主党 - 民主党,共和国 - 民主党等。

问题 - 速度!

仅处理 58000 个组需要将近 5 分钟。我在读研究生,我和我的教授谈过,他基本上告诉我使用哈希图。从我在其他 stackoverflow 搜索中看到的内容来看,我们可以使用 to_dict 和 list 来完成工作,其格式/语法尚不清楚。

temp2['All'] = temp2['Residence Address Line 1'].str.cat(temp2[['Residence Address Line 2']], sep=' - ')
df=temp2.groupby('All')

couples1 = pd.DataFrame(columns=["Voter_ID_Male", "Name_First_Male", "Name_Last_Male", "Birth_Date_Male", "Party_Affiliation_Male","Voter_ID_Female",  "Name_First_Female", "Name_Last_Female", "Birth_Date_Female", "Party_Affiliation_Female"])
couples2 = pd.DataFrame(columns=["Voter_ID_Male", "Name_First_Male", "Name_Last_Male", "Birth_Date_Male", "Party_Affiliation_Male","Voter_ID_Female",  "Name_First_Female", "Name_Last_Female", "Birth_Date_Female", "Party_Affiliation_Female"])

for name,group in df:



    if counter%30000 == 0 :
      print("Processed {} of {} items".format(counter,df.ngroups) )
    counter += 1

    #continue

    if group.shape[0]==2 and group[group.Gender == 'F'].shape[0] == 1 and group[group.Gender == 'M'].shape[0] == 1:

       #Start processing ...


标签: pythonpandasdataframe

解决方案


推荐阅读