【问题标题】:Drop consecutive duplicates across multiple columns - Pandas跨多列删除连续重复项 - Pandas
【发布时间】:2020-06-12 03:29:06
【问题描述】:

对此有几个问题,但未使用基于位置的多列索引: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: 必须只传递带有布尔值的 DataFrame

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

TypeError: 不支持的操作数类型 -: 'str' 和 '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 在这里不合适,因为我只想删除与前一行相同的行。我不想完全放弃相同的价值。

【问题讨论】:

  • 这就够了吗? df.groupby(['year','sale'],as_index=False).first()
  • 所以,不能是硬编码标签。将更新问题。性能也可能是 groupby 的一个问题

标签: python pandas


【解决方案1】:

我想删除 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

【讨论】:

  • 对不起,它们是字符串@Quang Hoang
  • @jonboy 查看shift 的更新。但是你为什么要/让yearsale 作为文本。直观地说,它们是数值型的。
  • 是的,它不代表我的实际数据。是个假套装。如果您将其更改为基于索引,那就太好了。 df = df[df.iloc[:,1:3].ne(df.iloc[:,1:3].shift()).any(1)].reset_index(drop = True)
  • 你也可以使用cols = df.iloc[:,1:3]; df[cols.ne(cols.shift()).any(1)]
猜你喜欢
  • 2012-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 1970-01-01
  • 2016-01-19
  • 2011-07-23
  • 2014-04-19
相关资源
最近更新 更多