Pandas用sum变换的时间太长了

2024-07-02 11:53:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas dataframe,它包含以下整数值列:

user_id, user_agent_id, appearances

行数各不相同,但超过40万行。我想创建一个新行totalappearances,它是每个用户的所有外观的总和。所以我要做的是:

^{pr2}$

我需要它,因为我想计算每个用户的用户代理id的百分比

^{3}$

我做同样的事情来计算百分比的最大值

dataframe['max_percent'] = dataframe['percent'].groupby(dataframe['user_id']).transform('max')

等等

问题是,虽然变换方法中的max方法需要大约5m,但sum方法需要更长的时间,即2sec。这是自然的吗?有没有更快的方法来获取total_appearances的信息?在


Tags: 方法用户iddataframepandas整数maxagent
1条回答
网友
1楼 · 发布于 2024-07-02 11:53:22

如果我理解正确的话,你可以用这样的方法将前两行合并成一个步骤:

# sample data
df
   appearances user_id
0            6     abc
1            3     abc
2            5     abc
3            8     def
4            4     gfd
5            2     uio
6            1     def
7            8     poi
8            3     fab

df['percent'] = df.groupby('user_id').appearances.apply(lambda x: x.div(np.sum(x)))

df
   appearances user_id   percent
0            6     abc  0.428571
1            3     abc  0.214286
2            5     abc  0.357143
3            8     def  0.888889
4            4     gfd  1.000000
5            2     uio  1.000000
6            1     def  0.111111
7            8     poi  1.000000
8            3     fab  1.000000

你看到这些变化带来的性能改善了吗?在

相关问题 更多 >