我的示例代码:
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万个数据行,我想知道最有效的方法
使用
query
筛选TYPE == 1
,sort_values
对LINE
进行排序,最后使用GroupBy.head
获得第一次出现:或者使用
drop_duplicates
,哪一种效率更高:相关问题 更多 >
编程相关推荐