跨多个列删除连续的重复项

2024-04-26 21:42:16 发布

您现在位置:Python中文网/ 问答频道 /正文

在这方面有一些问题,但不使用基于位置的多列索引:Pandas: Drop consecutive duplicates

我有一个df,它可能包含跨特定行的连续重复值。我只想删除最后两列的内容。使用下面的df,我想删除yearsale中的值相同的行

我使用下面的查询得到一个错误

import pandas as pd

df = pd.DataFrame({'month': [1, 4, 7, 10, 12, 12],
               'year': ['12', '14', '14', '13', '15', '15'],
              'sale': ['55', '40', '40', '84', '31', '32']})

cols = df.iloc[:,1:3]

# Option 1
df = df.loc[df[cols] != df['cols'].shift()].reset_index(drop = True)

ValueError: Must pass DataFrame with boolean values only

# Option 2
df = df[df.iloc[:,1:3].diff().ne(0).any(1)].reset_index(drop = True)

TypeError: unsupported operand type(s) for -: 'str' and 'str'

预期产出:

   month  year  sale
0      1  2012    55
1      4  2014    40
3     10  2013    84
4     12  2014    31
5     12  2014    32

注:

1)我需要使用索引标签来选择列,因为标签将更改。我需要一些液体

2)drop_duplicates在这里不合适,因为我只想删除与前一行相同的行。我不想完全删除相同的值


Tags: truedataframedfindexsaleyeardroppd
1条回答
网友
1楼 · 发布于 2024-04-26 21:42:16

我想删除yearsale中的值相同的行,这意味着您可以计算差值,检查它们在yearsale上是否等于零:

# if the data are numeric
# s = df[['year','sale']].diff().ne(0).any(1)

s = df[['year','sale']].ne(df[['year','sale']].shift()).any(1)
df[s]

输出:

   month  year  sale
0      1  2012    55
1      4  2014    40
3     10  2013    84
4     12  2014    31
5     12  2014    32

相关问题 更多 >