繁体   English   中英

Python Pandas - 根据其他列获取列的最小值并对另一列进行分组

[英]Python Pandas - Get min value of a column based on other column and group the other column

我有三列,它们看起来像这样:

Symbol    |  Type  |  Date    |  Value
----------------------------------------
Reliance  |  Buy   | 01/03/20 | 230000
Reliance  |  Sell  | 04/03/20 | 980000
Reliance  |  Buy   | 17/03/20 |  97000
TCS       |  Buy   | 10/03/20 | 120000
TCS       |  Buy   | 07/03/20 | 890000
TCS       |  Sell  | 05/03/20 | 300000

我想选择最小date和组value列和type列。 类型栏可以显示买入和卖出(一个符号只有两个)。

最终结果如下所示:

Symbol    |  Type  |  Date    |  Value
----------------------------------------
Reliance  |  Buy   | 01/03/20 |  327000
Reliance  |  Sell  | 04/03/20 |  980000
TCS       |  Buy   | 05/03/20 | 1010000
TCS       |  Sell  | 05/03/20 |  300000

到目前为止,我可以在没有日期列的情况下成功分组。 代码如下所示:

new_df = the_df.groupby(['symbol_', type_col])[value_col].sum().reset_index()

我试图这样做:

new_df = the_df.groupby(['symbol_', type_col, date_col])[value_col].sum().reset_index()
df_new = new_df[new_df.groupby('symbol_').date_of_initmation_to_company_.transform('min') == new_df[date_col]]

但它没有按预期工作。 实际上第二个像.transform没有做任何改变。 你能告诉我正确的方法吗?

然后

out = df.groupby(['Symbol','Type']).agg({'Date' : 'first' , 'Value' : 'sum'}).reset_index()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM