pandas datafram行和列之间的Python交互

2024-04-25 23:03:55 发布

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

我有这个数据帧:

print (df)
       exam       student
    0 French        a
    1 English       a
    2 Italian       a
    3 Chinese       b
    4 Russian       b
    5 German        b
    6 Chinese       c
    7 Spanish       c
    8 English       c
    9 French        c

我需要为每个学生找出和他参加相同考试的学生人数。在

应该是这样的:

^{pr2}$

学生A的总数是1,因为它只有一个学生参加普通考试(在本例中是学生C)。在

学生B的总人数是1,因为只有一个学生参加普通考试(在本例中是学生C)。在

学生C的总人数是2,因为这两个学生(学生A和B)都有共同的考试。在

有什么想法吗?在

提前谢谢你!在


Tags: 数据dfenglishstudent学生printgerman人数
1条回答
网友
1楼 · 发布于 2024-04-25 23:03:55

您可以先计算exam和{}的列联表,然后进行叉积检查学生之间是否存在考试重叠,并计算至少有一次共享考试的学生人数,并将结果映射到原始学生列:

cont_table = pd.crosstab(df.exam, df.student)

# cont_table.T.dot(cont_table) gives a table how many exams each student shared with 
# another student, -1 to exclude the student himself
shared_count = (cont_table.T.dot(cont_table) != 0).sum(0) - 1  
shared_count

#student
#a    1
#b    1
#c    2
#dtype: int64


df['total_st'] = df.student.map(shared_count)
df

enter image description here

相关问题 更多 >

    热门问题