有没有办法获得 groupby 中最后一个值的出现次数?

时间:2021-02-25 02:40:37

标签: python pandas pandas-groupby

这是一个示例数据框 -

df = pd.DataFrame({'ID': ['a1', 'a1', 'a1', 'a1', 'b2', 'b2', 'b2'],
                   'Price': [15, 12, 10, 10, 36, 34, 36]})

  ID  Price 
0 a1  15
1 a1  12
2 a1  10
3 a1  10
4 b2  36
5 b2  34
6 b2  36

这是预期的输出 -

df.groupby('ID').agg({'Price': ['last', 'last_count']})
ID  Price_last Price_last_count
a1  10         2
b2  36         2

我需要能够在 agg 中执行“last_count”操作。

3 个答案:

答案 0 :(得分:7)

logging

编辑以获得 OP 精确格式(由 Scott Boston 提供):

logging

输出:

df.groupby('ID')['Price'].agg(lastvalue = 'last', 
                              count = lambda x: sum(x==x.iloc[-1]) )


    lastvalue  count
ID                  
a1         10      2
b2         36      2

答案 1 :(得分:3)

首先找到 groupby use std::io; fn main() { loop { let mut string = String::new(); println!("Enter a value: "); let b = io::stdin().read_line(&mut string).expect("string"); let val: u32 = string.trim().parse().expect("Error"); println!("You typed: {:?}", val); } } 并找到尾部。

ID 进行 inner 合并

groupby df 的结果帧和 ['ID','Price'] count

代码如下:

Prices

答案 2 :(得分:0)

我写这个答案是为了使解决方案尽可能具有教学意义。总之,你得到每组的最后价格,并计算价格列等于每组最后观察到的价格的次数。

# Get the last value of each group
temp = df.groupby('ID').last()
# Merge df with this result
df = df.merge(temp, left_on='ID', right_index=True, how='inner')
# Declare column that evaluates if Price is equal to the last Price
df['count'] = df['Price_x'] == df['Price_y']
# Count times when Price equals Last price
df.groupby('ID')['count'].sum().to_frame()