Python 按分组方式从dataframe中选择行,并在给定列中选择max
我有一个如下结构的数据集。这是一个示例,因此请想象一个包含许多序列的数据帧。有几件事需要明确:Python 按分组方式从dataframe中选择行,并在给定列中选择max,python,pandas,Python,Pandas,我有一个如下结构的数据集。这是一个示例,因此请想象一个包含许多序列的数据帧。有几件事需要明确: 时间按降序排列。 在处创建的也按降序排列。 当出现新的源或货币时,时间和在重置时创建 index time app_v last source currency created_at 1 2019-10-23 3 4488 gol JPY 66 2 2019-10-23 29193
时间
按降序排列。
在处创建的也按降序排列。
当出现新的源
或货币
时,时间和在
重置时创建
index time app_v last source currency created_at
1 2019-10-23 3 4488 gol JPY 66
2 2019-10-23 29193 6687 gol JPY 65
3 2019-10-22 3 4587 gol JPY 64
4 2019-10-20 3 5687 gol JPY 63
5 2019-10-19 3 34787 gol JPY 62
6 2019-10-18 3 11789 gol JPY 61
...
预期输出是按来源货币和应用程序v
分组的最新最后一次时间。对于此示例,我们有两行对应:
index time app_v last source currency created_at
1 2019-10-23 3 4488 gol JPY 66
2 2019-10-23 29193 6687 gol JPY 65
您可以调用last
,计算每个组的最后一个值,并使用iloc
获取行值:
df.groupby(["source", "currency", "app_v"]).last().iloc[-1]
您可以使用name属性访问索引组值,如:
df.get_group(df.groupby('a').last().iloc[-1].name)
我快速修复了以下问题:ext_bal=ext_bal.loc[ext_bal['time']==ext_bal['time'].max()
,ext_bal
是数据帧的名称。但我希望能够用同样的方法选择最后n天。不知道怎么做。您只能使用我的方法,并且df.groupby([“源”、“货币”、“应用程序”])。last().iloc[-n]
将n
作为天数传递