【问题标题】:How to mark first entry per group satisfying some criterion?如何标记满足某些标准的每个组的第一个条目?
【发布时间】:2021-10-21 14:11:31
【问题描述】:

假设我有一些数据框,其中一列的某些值多次出现形成组(sn-p 中的列A)。现在我想创建一个新列,例如1 用于每个组的第一个 x(列 C)条目,0 在其他条目中。 我设法完成了第一部分,但我没有找到在xes 中包含条件的好方法,有没有好的方法?

import pandas as pd
df = pd.DataFrame(
    {
        "A": ["0", "0", "1", "2", "2", "2"],  # data to group by
        "B": ["a", "b", "c", "d", "e", "f"],  # some other irrelevant data to be preserved
        "C": ["y", "x", "y", "x", "y", "x"],  # only consider the 'x'
    }
)
target = pd.DataFrame(
    {
        "A": ["0", "0", "1", "2", "2", "2"],  
        "B": ["a", "b", "c", "d", "e", "f"], 
        "C": ["y", "x", "y", "x", "y", "x"],
        "D": [  0,   1,   0,   1,   0,   0]  # first entry per group of 'A' that has an 'C' == 'x'
    }
)
# following partial solution doesn't account for filtering by 'x' in 'C'
df['D'] = df.groupby('A')['C'].transform(lambda x: [1 if i == 0 else 0 for i in range(len(x))])

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    在你的情况下切片然后drop_duplicates 并分配回

    df['D'] = df.loc[df.C=='x'].drop_duplicates('A').assign(D=1)['D']
    df['D'].fillna(0,inplace=True)
    df
    Out[149]: 
       A  B  C    D
    0  0  a  y  0.0
    1  0  b  x  1.0
    2  1  c  y  0.0
    3  2  d  x  1.0
    4  2  e  y  0.0
    5  2  f  x  0.0
    

    【讨论】:

    • 谢谢!我不知道作业会尊重您第一行中的索引!我以一种对我来说更易读的方式重写了你的答案df['D'] = 0; df.loc[df.loc[df.C=='x'].drop_duplicates('A').index, 'D'] = 1。你觉得这有什么缺点吗?
    • @flawr 它会做同样的事情~
    猜你喜欢
    • 2019-09-02
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多