首页 > 编程问答 >如何获取列中负数最多的组并添加另一个条件来过滤组?

如何获取列中负数最多的组并添加另一个条件来过滤组?

时间:2024-08-03 17:14:06浏览次数:9  
标签:python pandas dataframe

这是对此已接受的 答案 的扩展。

我的数据帧:

import pandas as pd
df = pd.DataFrame(
    {
        'a': [-3, -1, -2, -5, 10, -3, -13, -3, -2, 1, 2, -100],
        'b': [1, 2, 3, 4, 5, 10, 80, 90, 100, 99, 1, 12]
    }
)

预期输出:

      a    b
5    -3   10
6   -13   80
7    -3   90
8    -2  100

逻辑:

a) 选择 a 中最长的负数条纹。|| |b) 例如,如果有两条大小相同的条纹,我想要

总和更大的一条。在 b 中有两条大小为4的条纹,但我想要第二条,因为 df 的总和更大。 b 我的尝试:

My Attempt:

import numpy as np
s = np.sign(df['a'])
df['g'] = s.ne(s.shift()).cumsum()
df['size'] = df.groupby('g')['g'].transform('size')
df['b_sum'] = df.groupby('g')['b'].transform('sum')

import numpy as np

def find_group_with_most_negatives(df):
    """
    Finds the group in DataFrame 'df' with the most negative numbers in column 'a',
    breaking ties by selecting the group with the largest sum in column 'b'.

    Args:
        df (pd.DataFrame): The input DataFrame with columns 'a' and 'b'.

    Returns:
        pd.DataFrame: A subset of the input DataFrame containing the group with the most negatives.
    """
    # Calculate sign changes and group consecutive negative/positive sequences
    s = np.sign(df['a'])
    df['g'] = s.ne(s.shift()).cumsum()

    # Calculate group size and sum of 'b' for each group
    df['size'] = df.groupby('g')['g'].transform('size')
    df['b_sum'] = df.groupby('g')['b'].transform('sum')

    # Find the group with the maximum size (number of negatives)
    max_size_group = df['size'].max()
    df_filtered_size = df[df['size'] == max_size_group]

    # If there are multiple groups with the same maximum size,
    # filter for the group with the maximum sum of 'b'
    if len(df_filtered_size) > 1:
        max_b_sum = df_filtered_size['b_sum'].max()
        df_filtered_size = df_filtered_size[df_filtered_size['b_sum'] == max_b_sum]

    return df_filtered_size[['a', 'b']]

# Apply the function to your DataFrame
result_df = find_group_with_most_negatives(df.copy())

# Print the result
print(result_df)

Explanation:

  1. Sign Changes and Grouping: This part remains the same as your attempt. It calculates sign changes in column 'a' and groups consecutive negatives.
  2. Group Calculations: Like your attempt, it calculates the size of each group (number of negatives) and the sum of values in column 'b' for each group.
  3. Filtering by Maximum Size: It identifies the group with the maximum size.
  4. Filtering by Maximum Sum (Tiebreaker): If there are multiple groups with the same maximum size, it further filters these groups to select the one with the maximum sum of 'b' values.
  5. Returning the Subset: Finally, it returns the subset of the DataFrame corresponding to the selected group.

This code will efficiently identify the desired group based on the specified criteria.

标签:python,pandas,dataframe
From: 78828009

相关文章

  • Python中动态类和动态方法的创建与调用
    借助于python的动态语言特性,很容易对对象进行添加方法或者属性,这也是python的灵活之一。动态生成类的属性及其方法在某些情况可能要根据不同的参数来动态生成不同的实例方法、静态方法、类方法。下面的例子中则展示了如何动态地向类中添加属性和方法。importtypesclassPers......
  • Python学习中最常见的10个列表操作问题
    列表是Python中使用最多的一种数据结果,如何高效操作列表是提高代码运行效率的关键,这篇文章列出了10个常用的列表操作,希望对你有帮助。1、迭代列表时如何访问列表下标索引普通版:items=[8,23,45]forindexinrange(len(items)):print(index,"-->",items[index])​......
  • Python中定义(创建)、调用函数及返回值
    1.定义(创建)函数要调用一个函数,首先要定义它。在Python中使用关键字def来定义一个函数。函数通常由函数名、参数列表以及一系列语句组成的函数体构成的。函数定义的一般格式如下:def函数名(参数列表):函数体例如:defsayhello(): print('hello')最简单的函数:defm......
  • python用List的内建函数list.sort进行排序
    对List进行排序,Python提供了两个方法方法1用List的内建函数listsort进行排序listsort(func=None,key=None,reverse=False)Python实对List进行排序,Python提供了两个方法方法1.用List的内建函数list.sort进行排序list.sort(func=None,key=None,reverse=False)>>>list=......
  • 禁用 GIL 的 Python 3.13 非常慢
    我对python3.12.0与使用3.13.0b3标志编译的python--disable-gil进行了简单的性能测试。该程序使用ThreadPoolExecutor或ProcessPoolExecutor执行斐波那契数列的计算。引入禁用GIL的PEP文档表示,存在一些开销,主要是由于有偏差......
  • 有没有办法阻止 setUp() 为 python 测试用例中的每个测试方法启动浏览器?
    我正在练习编写Web自动化测试用例,并且编写了一些函数来测试登录、在用户主页中查找我的用户名以及测试GitHub的注销功能。然而,我通过经验和阅读了解到setUp()是在每个测试方法之前启动的,而我的问题是在每个测试方法之前它都会打开一个新的浏览器。我希望我的所有测......
  • 尝试使用Python抓取需要先登录的网站但没有成功
    我正在尝试抓取一个需要登录的网站(我的路由器GUI),但无论我做了什么,我都会反复返回登录站点的源代码,而不是成功登录后出现的页面。我做了一些阅读,并意识到我需要返回POST请求的答案。我想我找到了它们并返回了所需的值,但仍然-似乎没有任何效果。我使用https://curl.tri......
  • 给python初学者的一些建议
    写在开篇关于Python,可以这么说,这几年借着数据科学、机器学习与人工智能的东风,Python老树开新花,在风口浪尖上居高不下。Python之所以这么受大家的青睐,是因为它语言简洁,上手容易,让非计算机专业的人员也能快速上手,享受编程开发带来的便利和福利。但Python再简单,它也是一......
  • Python中15个递归函数经典案例解析
    1.阶乘计算阶乘是一个常见的递归应用,定义为n!=n*(n-1)*…*1。deffactorial(n):ifn==0:return1else:returnn*factorial(n-1)print(factorial(5))#输出:1202.斐波那契数列斐波那契数列的每一项都......
  • 如何使用 python (使用服务帐户)在应用程序脚本 Web 应用程序上触发 doGet()?
    我想从返回json的应用程序脚本Web应用程序触发doGet(e)事件。我们的网络应用程序无法在我们的组织域之外访问,因此需要服务帐户。我执行了下面的代码,但“发生错误:401客户端错误”fromgoogle.oauth2importservice_accountfromgoogle.auth.transport.requestsimpor......