【问题标题】:Remove duplicated rows in groupby? [duplicate]删除groupby中的重复行? [复制]
【发布时间】:2019-01-22 17:07:42
【问题描述】:

我正在尝试在名为 volume 的数据框中创建一个新列。 DF 已经包含其他列,例如市场。我想要做的是按价格和公司分组,然后获取他们的数量并将其添加到一个名为 volume 的新列中。这是我所拥有的:

df['volume'] = df.groupby(['price', 'company']).transform('count')

这确实创建了一个新列,但是,它给了我所有的行。我不需要所有的行。例如,在转换之前我会得到 4 行,而在转换之后我仍然会得到 4 行但有一个新列。

market  company   price    volume
LA      EK        206.0     2
LA      SQ        206.0     1
LA      EK        206.0     2
LA      EK        36.0      3
LA      EK        36.0      3
LA      SQ        36.0      1
LA      EK        36.0      3

我想删除重复的行。有没有我可以用 groupby 做的查询,它只会显示这样的行:

market  company   price    volume
LA      EK        206.0     2
LA      SQ        206.0     1
LA      SQ        36.0      1
LA      EK        36.0      3

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    只需drop_duplicates 与列['market', 'company', 'price']

    >>> df.drop_duplicates(['market', 'company', 'price'])
      market company  price  volume
    0     LA      EK  206.0       2
    1     LA      SQ  206.0       1
    3     LA      EK   36.0       3
    5     LA      SQ   36.0       1
    

    【讨论】:

      【解决方案2】:

      您的数据包含重复数据,可能是因为您只包含了列的子集。您的数据中还需要价格以外的其他内容(例如,两个不同的日子可能以相同的价格收盘,但您不会汇总两者的交易量)。

      假设价格对于给定的时间戳、市场和公司是唯一的,并且您首先对时间戳列进行排序(如果有)(如果每个公司和市场只有一个价格,则不需要):

      df = pd.DataFrame({
          'company': ['EK', 'SQ', 'EK', 'EK', 'EK', 'SQ', 'EK'],
          'date': ['2018-08-13'] * 3 + ['2018-08-14'] * 4,
          'market': ['LA'] * 7,
          'price': [206] * 3 + [36] * 4})
      
      >>> (df.groupby(['market', 'date', 'company'])['price']
           .agg({'price': 'last', 'volume': 'count'}[['price', 'volume']]
           .reset_index()
      
        market        date company  price  volume
      0     LA  2018-08-13      EK    206       2
      1     LA  2018-08-13      SQ    206       1
      2     LA  2018-08-14      EK     36       3
      3     LA  2018-08-14      SQ     36       1
      

      【讨论】:

        猜你喜欢
        • 2022-12-04
        • 2021-02-24
        • 2019-04-12
        • 2015-07-08
        • 2012-07-27
        • 2016-09-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多