python - 如何向量化 pandas 中每个 ID# 的函数

标签 python pandas data-munging

此方法非常耗时/CPU 密集型,必须有更好的方法!有人可以帮助我在不使用循环的情况下对以下代码进行矢量化吗?基本上,我有一个 df,其中每个主题都有多行,每行都有一个值。我想添加一列,显示每个主题的最高值(主题的每一行都相同)。

import pandas as pd
import numpy as np
from numpy import nan

compare_table = pd.DataFrame({
    'id': [1,1,1,2,2,3,3,3],
    'day#': [1, 2, 3, 1, 2, 1, 2, 3],
    'random#': [2,5,1,6, 4, 5, 9, 3],
     'highest_random#': [nan, nan, nan, nan, nan, nan, nan, nan]}, columns=[
    'id', 'day#','random#','highest_random#'])

for element in list(compare_table['id'].unique()):
        highest_random = max(compare_table.loc[compare_table.loc[:,'id']==element, 'random#'])
        compare_table.loc[compare_table.loc[:,'id']==element, 'highest_random#']= highest_random

最佳答案

使用GroupBy.transform通过 maxmap 聚合 Series:

compare_table['highest_random#1'] = compare_table.groupby('id')['random#'].transform('max')

#a bit slowier alternative
s = compare_table.groupby('id')['random#'].max()
compare_table['highest_random#2'] = compare_table['id'].map(s)
print (compare_table)
   id  day#  random#  highest_random#  highest_random#1  highest_random#2
0   1     1        2              5.0                 5                 5
1   1     2        5              5.0                 5                 5
2   1     3        1              5.0                 5                 5
3   2     1        6              6.0                 6                 6
4   2     2        4              6.0                 6                 6
5   3     1        5              9.0                 9                 9
6   3     2        9              9.0                 9                 9
7   3     3        3              9.0                 9                 9

关于python - 如何向量化 pandas 中每个 ID# 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49881112/

相关文章:

python - 我需要知道如何让我的函数返回 float 。我对 float 标签的放置位置感到困惑

python - Pandas:将日期时间对象分配给时间间隔

python - 将基于正则表达式的选定列更改为百分比

Python,Pandas - 将函数应用于数据框中的列以仅替换某些项目的问题

python - 没有循环的数据集的特定组

php - 将 PHP 关联数组映射到 PDO 准备语句

python - 从 python 生成器接收 'return' 值的最佳方法

python - 从文件中写入和读取列表

python - :TypeError: argument of type 'function' is not iterable", 但在单独测试时有效

python - 从 pandas 交叉表返回平面系列