4

我正在尝试在名为 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
4

2 回答 2

9

只需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
于 2018-08-15T19:31:45.913 回答
1

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

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

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
于 2018-08-15T19:44:26.807 回答