获取按pandas中另一列排序的列划分的第一个匹配项

我的示例代码:

import pandas as pd
df = pd.DataFrame({"ID":['1','1','1','2','2'],
                   "LINE":['1','3','2','1','2'],
                   "TYPE":['0','1','1','1','0']})
# print results
print(df.head())

# a function to label the first type 1 for each ID sorted by line
# currently it only filters to type 1
def label (row):
    if row.TYPE == '1' :
        return True

# add the label in the dataframe
df['label'] = df.apply (lambda row: label(row), axis=1)

# print results
print(df.head())

我想为每个按LINE排序的唯一ID获得TYPE == 1的第一个匹配项。最终结果应该是:

  ID LINE TYPE label
0  1    1    0  None
1  1    3    1  None
2  1    2    1  True
3  2    1    1  True
4  2    2    0  None

我在这个问题中使用了一个示例,但实际上我正在处理300万个数据行,我想知道执行此操作的最有效方法。

转载请注明出处:http://www.xtpharmmachine.com/article/20230526/2337448.html