【发布时间】:2022-10-14 16:43:06
【问题描述】:
标签: python pandas dataframe filtering subset
标签: python pandas dataframe filtering subset
利用:
df1 = df.sort_values(['category_id','note'])
df1 = df1[~df.duplicated(['category_id']) | df1['category_id'].isna()].sort_index()
print (df1)
book_id category_id note
0 id1 c1 2
3 id4 c2 4
4 id5 NaN 1
5 id6 NaN 7
7 id8 c3 2
8 id9 NaN 8
9 id10 NaN 4
10 id11 NaN 9
【讨论】:
尝试:
res = df.sort_values('note', ascending=False)
res = res[(~res.duplicated('category_id')) | (res['category_id'].isna())]
.sort_index()
print(res)
book_id category_id note
1 id2 c1 5
4 id5 NaN 1
5 id6 NaN 7
6 id7 c2 6
7 id8 c3 2
8 id9 NaN 8
9 id10 NaN 4
10 id11 NaN 9
【讨论】:
排序具有 O(n*logn) 复杂度,因此最好尽可能使用线性时间方法。
您可以将boolean indexing 与两个掩码一起使用:
# is the row a NA?
m1 = df['category_id'].isna()
# is the row the max value for a non NA?
m2 = df.index.isin(df.groupby('category_id')['note'].idxmax())
# keep if any condition is met
out = df.loc[m1|m2]
输出:
book_id category_id note
1 id2 c1 5
4 id5 NaN 1
5 id6 NaN 7
6 id7 c2 6
7 id8 c3 2
8 id9 NaN 8
9 id10 NaN 4
10 id11 NaN 9
【讨论】: