获得按列划分的第一个匹配项,并按熊猫中的另一列排序

问题描述 投票:0回答:1

我的示例代码:

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())

我想获得按TYPE == 1排序的每个唯一IDLINE的首次出现。最终结果应为:

  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万个数据行,并想知道执行此操作的最有效方法。

python pandas
1个回答
0
投票

使用query过滤TYPE == 1,使用sort_values排序LINE,最后使用GroupBy.head首次出现:

s = df.query('TYPE == "1"').sort_values('LINE').groupby('ID')['TYPE'].head(1)
df['label'] = df.index.isin(s.index)

  ID LINE TYPE  label
0  1    1    0  False
1  1    3    1  False
2  1    2    1   True
3  2    1    1   True
4  2    2    0  False
© www.soinside.com 2019 - 2024. All rights reserved.