Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

Pandas groupby efficiency and avoiding repetitive operations

Pandas 1.0.5

import pandas as pd

data = [
        [1, 1, '2020-01-01', 'McDonalds', '94521', 'US', '5812'],
        [2, 1, '2020-01-02', 'Burger King', '94521', 'US', '5812'],
        [3, 1, '2020-01-03', 'Taco Bell', '94521', 'US', '5812'],
        [4, 2, '2020-02-01', 'Arbys', '94522', 'US', '5812'],
        [5, 2, '2020-02-02', 'Carls Jr', '94522', 'US', '5812'],
        [6, 2, '2020-02-03', 'Jack In The Box', '94522', 'US', '5812'],
        [7, 1, '2020-03-01', 'McDonalds', '94521', 'US', '5812'],
        [8, 1, '2020-03-02', 'Burger King', '94521', 'US', '5812'],
        [9, 1, '2020-03-03', 'Taco Bell', '94521', 'US', '5812'],
        [10, 1, '2020-03-04', 'Taco Bell', '94521', 'US', '5812'],
        ]

d = pd.DataFrame(data, columns = ['id', 'card_id', 'trandt', 'merchant', 'zipcode', 'country', 'mcc'])

d['merchant_count'] = d.groupby(['card_id', 'merchant']).cumcount()
d['zipcode_count'] = d.groupby(['card_id', 'zipcode']).cumcount()
d['country_count'] = d.groupby(['card_id', 'country']).cumcount()
d['mcc_count'] = d.groupby(['card_id', 'mcc']).cumcount()
#etc

The data is 50 million rows. I will use 100 such groupbys to add 100 columns. All groupbys start with card_id for the first column, and various columns for the second column, as shown in this example. The above code works, but is not efficient because it groups by the same card_id repetitively.

Is there any way to make this more efficient? Any way to avoid grouping by card_id over and over again?

question from:https://stackoverflow.com/questions/65557395/pandas-groupby-efficiency-and-avoiding-repetitive-operations

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...