【发布时间】:2021-10-20 02:32:43
【问题描述】:
我有这个数据框:
df = pd.DataFrame({
'thread_id': [0,0,1,1,1,2,2],
'message_id_in_thread': [0,1,0,1,2,0,1],
'text': ['txt0', 'txt1', 'txt2', 'txt3', 'txt4', 'txt5', 'txt6']
}).set_index(['thread_id', 'message_id_in_thread'])
我想保留所有最后的第二级行,这意味着:
- 对于
thread_id==0,我想保留行message_id_in_thread==1 - 对于
thread_id==1,我想保留行message_id_in_thread==2 - 对于
thread_id==2,我想保留行message_id_in_thread==1
这可以通过df.iterrows()轻松实现,但我想知道是否有任何直接索引方法。
我寻找类似df.loc[(:, -1)] 的东西,它从所有 (:) 级别 1 组中选择该块/组的最后 (-1) 行,但显然这不起作用。
【问题讨论】:
-
嗯。看起来你可以在 thread_id 上分组并选择最后一行
.last
标签: python pandas dataframe indexing pandas-groupby