按一列分组,从两列中找出第一列

2024-05-14 19:09:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧geomerge,我需要按一列grpno.分组,选择列MaxOfcount percent的第一个和列state code的第一个,并显示grpno.。我将它们重命名为FirstOfMaxOfState count percentFirstOfstate code

我的输入数据帧:

      count percent  grpno. state code  MaxOfcount percent
0          14.78       1         CA               14.78
1           0.00       2         CA                0.00
2           0.00       2         FL                0.00
3           8.80       3         CA                8.80
4           0.00       6         NC                0.00
5           0.00       5         NC                0.00
6          59.00       4         MA               59.00

我的输出数据帧:

      FirstOfMaxOfState count percent  state pool number FirstOfstate code
0                            14.78                  1                CA
1                             0.00                  2                CA
2                             8.80                  3                CA
3                            59.00                  4                MA
4                             0.00                  5                NC
5                             0.00                  6                NC

有人能帮忙吗?你知道吗


Tags: 数据countcodeca重命名statepercentnc
1条回答
网友
1楼 · 发布于 2024-05-14 19:09:17

删除不需要的列,按grpno分组,获取第一个值,并展平多索引:

df2 = df.drop('count percent', 1).groupby('grpno.').take([0]).reset_index(0)

重命名列:

mapping = {'state code':'FirstOfstate code' ,
           'grpno.': 'state pool number',
           'MaxOfcount percent': 'FirstOfMaxOfState count percent'}
df2.rename_axis(mapping, axis=1)

结果:

>>> df2

   state pool number  FirstOfMaxOfState count percent FirstOfstate code
0                  1                            14.78                CA
1                  2                             0.00                CA
3                  3                             8.80                CA
6                  4                            59.00                MA
5                  5                             0.00                NC
4                  6                             0.00                NC

相关问题 更多 >

    热门问题