Python Pandas groupby forloop&;Idxmax

Python Pandas groupby forloop&;Idxmax,python,for-loop,pandas,Python,For Loop,Pandas,我有一个数据帧,必须在三个级别上分组,然后返回最高值。每一天都有一个独特的价值回报,我想找到最高的回报和细节 data.groupby(['Company','Product','Industry'])['ROI'].idxmax() 回报将表明: Target - Dish Soap - House had a 5% ROI on 9/17 Best Buy - CDs - Electronics had a 3% ROI on 9/3 是最高的 以下是一些示例

我有一个数据帧,必须在三个级别上分组,然后返回最高值。每一天都有一个独特的价值回报,我想找到最高的回报和细节

data.groupby(['Company','Product','Industry'])['ROI'].idxmax()
回报将表明:

Target   - Dish Soap - House       had a 5% ROI on 9/17
Best Buy - CDs       - Electronics had a 3% ROI on 9/3
是最高的

以下是一些示例数据:

+----------+-----------+-------------+---------+-----+
| Industry | Product   | Industry    | Date    | ROI |
+----------+-----------+-------------+---------+-----+
| Target   | Dish Soap | House       | 9/17/13 | 5%  |
| Target   | Dish Soap | House       | 9/16/13 | 2%  |
| BestBuy  | CDs       | Electronics | 9/1/13  | 1%  |
| BestBuy  | CDs       | Electroincs | 9/3/13  | 3%  |
| ...

不确定这是for循环还是使用.ix.

我想,如果我理解正确,您可以使用
groupby
idxmax()
收集一系列索引值,然后使用
loc
df
中选择这些行:

idx =  data.groupby(['Company','Product','Industry'])['ROI'].idxmax()
data.loc[idx]
另一个选项是使用
reindex

data.reindex(idx)
在我手头碰巧有一个(不同的)数据帧上,似乎
reindex
可能是更快的选项:

In [39]: %timeit df.reindex(idx)
10000 loops, best of 3: 121 us per loop

In [40]: %timeit df.loc[idx]
10000 loops, best of 3: 147 us per loop

我想,如果我理解正确,您可以使用
groupby
idxmax()
收集一系列索引值,然后使用
loc
df
中选择这些行:

idx =  data.groupby(['Company','Product','Industry'])['ROI'].idxmax()
data.loc[idx]
另一个选项是使用
reindex

data.reindex(idx)
在我手头碰巧有一个(不同的)数据帧上,似乎
reindex
可能是更快的选项:

In [39]: %timeit df.reindex(idx)
10000 loops, best of 3: 121 us per loop

In [40]: %timeit df.loc[idx]
10000 loops, best of 3: 147 us per loop

如果max(和朋友们)在groupby和df中都接受了一个密钥,那就太酷了。这可能会更快…是的,我希望
NumPy
有一个
key
参数用于
max
sort
!(不过,正如您所说,它可能没有包括在内,因为为NumPy数组或数据帧的每个元素调用Python函数会严重阻碍速度。)我认为这应该是
data.loc
而不是
data.iloc
。至少这对我是有效的。@Sachin_-ruk:非常感谢你的更正。事实上,它应该是
data.loc
,因为
idxmax
返回标签,而不是索引位置。如果max(和friends)在groupby和df中都接受一个键,那就太酷了。这可能会更快…是的,我希望
NumPy
有一个
key
参数用于
max
sort
!(不过,正如您所说,它可能没有包括在内,因为为NumPy数组或数据帧的每个元素调用Python函数会严重阻碍速度。)我认为这应该是
data.loc
而不是
data.iloc
。至少这对我是有效的。@Sachin_-ruk:非常感谢你的更正。实际上,它应该是
data.loc
,因为
idxmax
返回标签,而不是索引位置。