gpt4 book ai didi

python - 使用组行创建新的数据框

转载 作者:行者123 更新时间:2023-11-30 22:31:13 25 4
gpt4 key购买 nike

我想提取组中每个数据帧的行,并从中创建新的数据帧,这样一个新的数据帧仅包含该组的第一行,另一个新的数据帧包含第二行,另一个包含第三行,等等..例如,我的数据框是:

raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],
'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
df = pd.DataFrame(raw_data, columns = ['regiment', 'name', 'preTestScore', 'postTestScore'])
df

regiment name preTestScore postTestScore
0 Nighthawks Miller 4 25
1 Nighthawks Jacobson 24 94
2 Nighthawks Ali 31 57
3 Nighthawks Milner 2 62
4 Dragoons Cooze 3 70
5 Dragoons Jacon 4 25
6 Dragoons Ryaner 24 94
7 Dragoons Sone 31 57
8 Scouts Sloan 2 62
9 Scouts Piger 3 70
10 Scouts Riani 2 62
11 Scouts Ali 3 70

我将其分组为:

gb = df.groupby("regiment")

regiment name preTestScore postTestScore
8 Scouts Sloan 2 62
9 Scouts Piger 3 70
10 Scouts Riani 2 62
11 Scouts Ali 3 70
------------------
regiment name preTestScore postTestScore
0 Nighthawks Miller 4 25
1 Nighthawks Jacobson 24 94
2 Nighthawks Ali 31 57
3 Nighthawks Milner 2 62
------------------
regiment name preTestScore postTestScore
4 Dragoons Cooze 3 70
5 Dragoons Jacon 4 25
6 Dragoons Ryaner 24 94
7 Dragoons Sone 31 57
------------------

我想创建数据框,例如:

第一行的数据框:

    regiment        name         preTestScore  postTestScore
8 Scouts Sloan 2 62
0 Nighthawks Miller 4 25
4 Dragoons Cooze 3 70

第二行的数据框:

   regiment          name        preTestScore  postTestScore
9 Scouts Piger 3 70
1 Nighthawks Jacobson 24 94
5 Dragoons Jacon 4 25

等等。

我正在考虑使用 Group.apply() 但我不太确定。

非常感谢!

最佳答案

您可能可以使用带有 cumcount 的嵌套 groupby 来完成此操作,例如这将对所有第一次出现的团、所有第二次出现的团进行分组,等等:

In []:
[g for _, g in df.groupby(df.groupby('regiment').cumcount())]

Out[]:
[ regiment name preTestScore postTestScore
0 Nighthawks Miller 4 25
4 Dragoons Cooze 3 70
8 Scouts Sloan 2 62,
regiment name preTestScore postTestScore
1 Nighthawks Jacobson 24 94
5 Dragoons Jacon 4 25
9 Scouts Piger 3 70,
regiment name preTestScore postTestScore
2 Nighthawks Ali 31 57
6 Dragoons Ryaner 24 94
10 Scouts Riani 2 62,
regiment name preTestScore postTestScore
3 Nighthawks Milner 2 62
7 Dragoons Sone 31 57
11 Scouts Ali 3 70]

关于python - 使用组行创建新的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45874279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com