我有这个数据:
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我需要为每个学生找到和他一样参加考试的学生人数。
应该是这样的:
exam student total_st
0 French a 1
1 English a 1
2 Italian a 1
3 Chinese b 1
4 Russian b 1
5 German b 1
6 German c 2
7 Spanish c 2
8 English c 2
9 French c 2学生A的总人数是1,因为只有一个学生有共同的考试(在这种情况下是与学生C)。
学生B的总人数是1,因为它有普通考试,只有一个学生(在这种情况下与学生C)。
学生C的总人数是2,因为它与两个学生(学生A和B)都有共同的考试。
有什么想法吗?
提前谢谢你!
发布于 2017-03-11 16:37:29
您可以首先计算exam和student的偶然性表,然后执行交叉乘积检查学生之间是否存在考试重叠,并统计至少有一次共享考试的学生人数,并将结果映射到原始的学生列:
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

https://stackoverflow.com/questions/42737608
复制相似问题