Python Pandas : Going through a list of cycles and making point of interest

标签 python pandas max

为了更容易地解释我的问题,我创建了一个数据集:

data = {'Cycle': ['Set1', 'Set1', 'Set1', 'Set2', 'Set2', 'Set2', 'Set2'],
        'Value': [1, 2.2, .5, .2,1,2.5,1]}

我想创建一个循环,遍历“循环”列,并用字母 A 标记每个循环的最大值,用字母 B 标记最小值,以输出如下内容:

POI = {'Cycle': ['Set1', 'Set1', 'Set1', 'Set2', 'Set2', 'Set2', 'Set2'],
        'Value': [1, 2.2, .5, .2,1,2.5,1],
         'POI': [0, 'A','B','B',0,'A',0]}

df2 = pd.DataFrame(POI)

我是 Python 新手,所以尽可能多的细节会非常有帮助,而且我不太确定如何单独完成每个循环来获取这些值,所以解释一下会很棒。

谢谢

最佳答案

使用numpy.selectgroupby.transform:

g = df.groupby('Cycle')['Value']
df['POI'] = np.select([df['Value'].eq(g.transform('max')),
                       df['Value'].eq(g.transform('min'))],
                      ['A', 'B'])

# if you want 0 as default value (not '0')
df['POI'] = df['POI'].replace('0', 0)

输出:

  Cycle  Value POI
0  Set1    1.0   0
1  Set1    2.2   A
2  Set1    0.5   B
3  Set2    0.2   B
4  Set2    1.0   0
5  Set2    2.5   A
6  Set2    1.0   0

关于Python Pandas : Going through a list of cycles and making point of interest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73547066/

相关文章:

python - PyCurl 执行 POST 时的奇怪行为

Python 将 StringIO 转换为二进制

python - 将百分位值分配给python中的一长串股票

list - haskell 列表中第二大元素

python - Conda 命令在命令提示符下工作但不在 bash 脚本中工作

python - 在 Python if 语句中使用列表和元组

python - Pandas - 列标题到行值

python-3.x - 计算行之间的时间增量作为第二列每个元素的最大时间和最小时间之间的差

java - 比较整数变量以获取范围内的最大值

python - 如何在 Python 3 中解码 HTTP 请求头和正文?