python - 处理pandas groupby中的项目很慢?我们应该使用哈希图吗?
问题描述
我们有一个选民登记数据的熊猫数据框。我们所做的如下:
- 按地址对选民进行分组——这会在数据框中产生组,然后我们可以处理这些组。
- 鉴于这些组,我们现在遍历它们中的每一个,其中每个组有两个不同性别的人,我们可能将他们归类为一对。
- 如果我们有一对夫妇,我们会进一步将他们分成具有相同或不同政党隶属关系的人。换句话说,民主党 - 民主党,共和国 - 民主党等。
问题 - 速度!
仅处理 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 ...
解决方案
推荐阅读
- angular - 没有提供 HttpResponse - angular5 StaticInjectorError (AppModule)[AppComponent -> HttpResponse]
- scala - 基于 Spark DF 中 2 列的组合过滤行
- node.js - Firebase - TypeError:admin.auth(...).createUserWithEmailAndPassword 不是函数
- python - 使用 Python 解码 KeyNote IWA protobuf 数据
- python-3.x - 下一个按钮引发错误
- python - 置换 Kronecker 产品串
- kubernetes - GKE:停止实例时出现 502
- c - AES CTR OpenSSL 命令行与 EVP_aes_128_ctr C 代码不匹配
- python - MatPlotlib 中的方形气泡图
- c++ - 如何使用 vindex 和 _mm_i32gather_epi32 缩放来收集元素?