删除熊猫数据框中的行,并且在特定列中具有相同(和相邻)的条目

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

我有一个数据框,在“项目”列中有一些重复项。

enter image description here

我想删除重复项(相邻)的行,但保留最后一行,即摆脱红色,但保持绿色

enter image description here

然后我想创建一个新列,假定苹果是一个起点,下一行是距此的时间增量。

enter image description here

pandas
1个回答
0
投票

IIUC,尝试:

df.assign(Item_cnt=(df['Item'] != df['Item'].shift()).cumsum())\
  .drop_duplicates(['Item','Item_cnt'], keep='last')

输出:

      Item  datetime  Item_cnt
2   apples       1.2         1
3  oranges       2.3         2
4   apples       2.5         3
5  bananas       2.7         4
© www.soinside.com 2019 - 2024. All rights reserved.