我的示例代码:
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
排序的每个唯一ID
的LINE
的首次出现。最终结果应为:
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万个数据行,并想知道执行此操作的最有效方法。
使用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