【问题标题】:Iterate over a groupby dataframe to operate in each row迭代 groupby 数据帧以在每一行中操作
【发布时间】:2020-09-07 02:34:05
【问题描述】:

我有一个这样的数据框:

    subject  trial  attended
0         1      1         1
1         1      3         0
2         1      4         1
3         1      7         0
4         1      8         1
5         2      1         1
6         2      2         1
7         2      6         1
8         2      8         0
9         2      9         1
10        2     11         1
11        2     12         1
12        2     13         1
13        2     14         1
14        2     15         1
  1. 我想分组主题。
  2. 然后迭代 GroupBy 数据帧的每一行。
  3. 如果对于一行 'attended' == 1,则将变量 sum_reactive 增加 1。
  4. 如果 sum_reactive 变量达到 == 4,则在字典中添加变量 sum_reactive 达到值 4 的“subject”和“trial”。

我试图为此定义一个函数,但它不起作用:

def count_attended():
    sum_reactive = 0
    dict_attended = {}
    for i, g in reactive.groupby(['subject']):
        for row in g:
            if g['attended'][row] == 1:
                sum_reactive += 1
                if sum_reactive == 4:
                   dict_attended.update({g['subject'] : g['trial'][row]})
                   return dict_attended

    return dict_attended

我认为我不清楚如何在每个 GroupBy 数据框中进行迭代。我是使用熊猫的新手。

【问题讨论】:

    标签: python pandas loops dictionary group-by


    【解决方案1】:

    IIUC 试试,

    df = df.query('attended == 1')
    df.loc[df.groupby('subject')['attended'].cumsum() == 4, ['subject', 'trial']].to_dict(orient='record')
    

    输出:

    [{'subject': 2, 'trial': 9}]
    

    使用 groupbycumsum 将进行计数,然后检查该值何时等于 4 以创建布尔系列。您可以使用此布尔系列进行布尔索引以将数据框过滤到某些行。最后,使用锁定和列过滤选择主题和试验。

    【讨论】:

    • 您应该首先放弃所有无人参与的试验。否则,您的输出将包括正确输出之后的输出。
    • @QuangHoang 我明白了。谢谢!
    猜你喜欢
    • 2021-07-09
    • 2022-08-17
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    相关资源
    最近更新 更多