![](/img/trans.png)
[英]How to group by current index in a multiple chained groupby-agg in pandas?
[英]Pandas groupby(),agg() - how to return results without the multi index?
我有一个 dataframe:
pe_odds[ [ 'EVENT_ID', 'SELECTION_ID', 'ODDS' ] ]
Out[67]:
EVENT_ID SELECTION_ID ODDS
0 100429300 5297529 18.00
1 100429300 5297529 20.00
2 100429300 5297529 21.00
3 100429300 5297529 22.00
4 100429300 5297529 23.00
5 100429300 5297529 24.00
6 100429300 5297529 25.00
当我使用 groupby 和 agg 时,我得到一个多索引的结果:
pe_odds.groupby( [ 'EVENT_ID', 'SELECTION_ID' ] )[ 'ODDS' ].agg( [ np.min, np.max ] )
Out[68]:
amin amax
EVENT_ID SELECTION_ID
100428417 5490293 1.71 1.71
5881623 1.14 1.35
5922296 2.00 2.00
5956692 2.00 2.02
100428419 603721 2.44 2.90
4387436 4.30 6.20
4398859 1.23 1.35
4574687 1.35 1.46
4881396 14.50 19.00
6032606 2.94 4.20
6065580 2.70 5.80
6065582 2.42 3.65
100428421 5911426 2.22 2.52
我尝试使用 as_index 来返回没有 multi_index 的结果:
pe_odds.groupby( [ 'EVENT_ID', 'SELECTION_ID' ], as_index=False )[ 'ODDS' ].agg( [ np.min, np.max ], as_index=False )
但它仍然给了我一个多索引。
我可以使用.reset_index(),但是很慢:
pe_odds.groupby( [ 'EVENT_ID', 'SELECTION_ID' ] )[ 'ODDS' ].agg( [ np.min, np.max ] ).reset_index()
pe_odds.groupby( [ 'EVENT_ID', 'SELECTION_ID' ] )[ 'ODDS' ].agg( [ np.min, np.max ] ).reset_index()
Out[69]:
EVENT_ID SELECTION_ID amin amax
0 100428417 5490293 1.71 1.71
1 100428417 5881623 1.14 1.35
2 100428417 5922296 2.00 2.00
3 100428417 5956692 2.00 2.02
4 100428419 603721 2.44 2.90
5 100428419 4387436 4.30 6.20
如何在没有多索引的情况下使用 groupby 和/或 agg function 的参数返回结果。 并且不必求助于使用reset_index()?
以下电话:
>>> gr = df.groupby(['EVENT_ID', 'SELECTION_ID'], as_index=False)
>>> res = gr.agg({'ODDS':[np.min, np.max]})
>>> res
EVENT_ID SELECTION_ID ODDS
amin amax
0 100429300 5297529 18 25
1 100429300 5297559 30 38
返回带有mulit-index 列的框架。 如果您不希望列成为多索引,您可以执行以下操作:
>>> res.columns = list(map(''.join, res.columns.values))
>>> res
EVENT_ID SELECTION_ID ODDSamin ODDSamax
0 100429300 5297529 18 25
1 100429300 5297559 30 38
我已经采纳了 Kim 的评论并将其优化(您根本不需要 use.to_flat_index())到下面的代码中。 我相信这是最 Pythonic(易于理解)和优雅的方法:
df.columns = ["_".join(col_name).rstrip('_') for col_name in df.columns]
一个示例用法是:
>>> df.columns = ["_".join(col_name).rstrip('_') for col_name in df.columns]
>>> df
EVENT_ID SELECTION_ID ODDS_amin ODDS_amax
0 100429300 5297529 18 25
1 100429300 5297559 30 38
也可以使用pipe
方法、 set_axis
和链接(我相信它更具可读性)来删除列上的 multi_index。
(
pe_odds
.groupby(by=['EVENT_ID', 'SELECTION_ID'] )
.agg([ np.min, np.max ])
.pipe(lambda x: x.set_axis(x.columns.map('_'.join), axis=1))
)
这是 output 没有重置索引。
ODDS_amin ODDS_amax
EVENT_ID SELECTION_ID
100429300 5297529 18.0 25.0
100429300 5297559 30.0 38.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.