python在多个组中选一组_python-使用 pandas 在每个groupby组的列中选择最大的N
我的df:
{'city1': {0: 'Chicago',
1: 'Chicago',
2: 'Chicago',
3: 'Chicago',
4: 'Miami',
5: 'Houston',
6: 'Austin'},
'city2': {0: 'Toronto',
1: 'Detroit',
2: 'St.Louis',
3: 'Miami',
4: 'Dallas',
5: 'Dallas',
6: 'Dallas'},
'p234_r_c': {0: 5.0, 1: 4.0, 2: 2.0, 3: 0.5, 4: 1.0, 5: 4.0, 6: 3.0},
'plant1_type': {0: 'COMBCYCL',
1: 'COMBCYCL',
2: 'NUKE',
3: 'COAL',
4: 'NUKE',
5: 'COMBCYCL',
6: 'COAL'},
'plant2_type': {0: 'COAL',
1: 'COAL',
2: 'COMBCYCL',
3: 'COMBCYCL',
4: 'COAL',
5: 'NUKE',
6: 'NUKE'}}
我想執(zhí)行2個groupby操作,并使用列p234_r_c進行每個組中最大的1個操作.
第一分組= [‘plant1_type’,’plant2_type’,’city1′]
第二分組= [‘plant1_type’,’plant2_type’,’city2′]
因此,我將執(zhí)行以下操作:
df.groupby(['plant1_type','plant2_type','city1'])['p234_r_c'].\
nlargest(1).reset_index()
plant1_type plant2_type city1 level_3 p234_r_c
0 COAL COMBCYCL Chicago 3 0.5
1 COAL NUKE Austin 6 3.0
2 COMBCYCL COAL Chicago 0 5.0
3 COMBCYCL NUKE Houston 5 4.0
4 NUKE COAL Miami 4 1.0
5 NUKE COMBCYCL Chicago 2 2.0
第一組的結果很有意義.但是,我對第二分組的結果感到困惑:
df.groupby(['plant1_type','plant2_type','city2'])['p234_r_c'].\
nlargest(1).reset_index()
index p234_r_c
0 0 5.0
1 1 4.0
2 2 2.0
3 3 0.5
4 4 1.0
5 5 4.0
6 6 3.0
結果中的列plant1_type,plant2_type和city2發(fā)生了什么?它們不應該像在第一個groupby的結果中出現(xiàn)plant1_type,plant2_type和city1一樣出現(xiàn)在結果中嗎?
總結
以上是生活随笔為你收集整理的python在多个组中选一组_python-使用 pandas 在每个groupby组的列中选择最大的N的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为手机8.0.0怎么找到云相册_华为G
- 下一篇: 乾坤 微前端_最全汇总之微前端知识和实战