gpt4 book ai didi

python - 至少返回 DataFrame 的前 n 行

转载 作者:行者123 更新时间:2023-12-04 15:03:17 28 4
gpt4 key购买 nike

我正在使用 panda 和 python,并且我有类似于下面的 DF:

id    student   courses
0 A 1
1 F 2
2 B 5
3 C 2
4 D 4
5 H 5

并且我想至少选择类(class)最多的前 3 名学生。得到这样的东西:

id  student courses
2 B 5
5 H 5
4 D 4
1 F 2
3 C 2

返回的 DF 有 5 行,因为我需要显示所有参加类(class)的学生与前 3 名的最后一名学生均等。

我的代码:

sorted_list = students_DF.sort_values(by=["courses"], ascending=False)
n=3 #top-3
return_df = sorted_list[:n]
for i, row in sorted_list.iterrows():
if return_df.iloc[n-1]['mag'] == sorted_list.iloc[n]['mag']:
return_df.append(sorted_list.iloc[n], ignore_index=True)

出于某种原因,我无法让它追加行。任何帮助。

最佳答案

尝试 np.unique 提取最大类(class),然后 isin:

max_courses = np.unique(df.courses)[-3:]

df[df.courses.isin(max_courses)]

输出:

   id student  courses
1 1 F 2
2 2 B 5
3 3 C 2
4 4 D 4
5 5 H 5

关于python - 至少返回 DataFrame 的前 n 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66591377/

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