![](/img/trans.png)
[英]Python Pandas - filter pandas dataframe to get rows with minimum values in one column for each unique value in another column
[英]With Pandas, get value from one column in dataframe (for each group), based on minimum value of second column
假设我们有一个包含 3 列的数据the_customer
: the_customer
、 the_date
和the_amount
。 我们需要为每个用户创建一个数据the_amount
,该数据the_amount
具有与每个用户的the_amount
的最早/最小值相关联的the_date
。 这是我们目前正在做的事情:
each_users_first_amount = our_data[['the_customer', 'the_date', 'the_amount']]\
.sort_values(by='the_date', ascending = True)\
.groupby('the_customer', as_index=False)\
.apply(lambda x: x.head(1))\
.rename(columns = { 'the_date': 'earliest_date', 'the_amount': 'first_amount' })
这种方法在技术上是有效的,但是由于某种原因,这个函数在我们的数据上运行得很慢,我不确定链中的哪个方法导致函数运行缓慢( .apply
?)。 这似乎也很“hacky”,特别是使用head
抓取第一行的.apply(lambda x: x.head(1))
行,这是因为我们之前已排序。
特别是,如果可以以某种方式使用.agg()
来完成这可能会有所帮助,因为我们已经在另一个方法链中使用.agg()
来对数据进行分组并计算分组指标。
使用聚合函数对于更大尺寸的数据帧效率不高,在处理更大的数据帧时,它比交互消耗更多的时间。 但是,在您的代码中,应用函数或迭代是唯一可能的选择,因此您无法替换它。 但我认为代码中的时间过程是排序。 在 groupby 之后使用 sort 可能会降低时间复杂度,因为对它的许多小子集进行排序比对整个数据帧进行排序更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.