【问题标题】:How to get the first item in a group by that meets a certain condition in pandas?如何在熊猫中获得满足特定条件的组中的第一项?
【发布时间】:2018-12-06 22:17:47
【问题描述】:

我有以下代码:

grouped_stats = stats.groupby( stats.last_mv.ne( stats.last_mv.shift()).cumsum() )

last_mv 是十进制值 在上面的代码中,我按连续值分组

我正在尝试两种方法来获得比组 last_mv 值中的第一项高 0.25% 的第一个值。换句话说,我已经按连续的 last_mv 值分组,我想选择每个组中的第一个,乘以 1.025,然后找到组中与该值匹配的第一个值(如果存在)

我试过了:

grouped_stats.filter(lambda x: x.last_mv >= (x.first().last_mv * 1.025))

但我无法使用 .first() 访问组中的第一行,因为我认为我不会

我也试过了

grouped_stats.loc[ grouped_stats.last_mv >= (grouped_stats.first().last_mv * 1.025) ]

但我收到错误:“无法访问 'DataFrameGroupBy' 对象的可调用属性 'loc',请尝试使用 'apply' 方法”

【问题讨论】:

  • 你能添加一些示例数据和预期输出吗?
  • 能否请您在代码标签中提及示例输入和预期示例输出,然后告诉我们。

标签: python python-3.x pandas


【解决方案1】:

我相信您需要 transform 来获得与原始 DataFrame 相同大小的 Series,并由每个组的第一个值填充:

stats[ stats.last_mv >= (grouped_stats.last_mv.transform('first') * 1.025) ]

【讨论】:

  • 我收到“ValueError: setting an array element with a sequence”。因为 grouped_stats.last_mv 仍然返回“
  • @user2330270 - grouped_stats.last_mv.transform('first') 的工作情况如何?
  • 我的意思是条件前的位 >= ..... grouped_stats.last_mv.transform('first') 正确返回每个组的第一项
猜你喜欢
  • 2016-08-22
  • 2023-01-31
  • 2020-09-28
  • 1970-01-01
  • 2019-11-13
  • 2023-02-06
  • 2020-02-22
  • 2019-06-04
  • 2022-07-22
相关资源
最近更新 更多