计数行,其中只有特定列是Tru

2024-06-14 11:46:07 发布

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

我有一个布尔数据帧。如果每一行是,让我们说一个“教室”,每一列标题是一个“学生id”。以教室为索引,我只想知道以下几点:

  • 对于不同的分组(学生ID),他们有多少次,只有他们共享一个教室

数据帧如下所示:

df =pd.DataFrame({'classroom_id':[1,2,3,4], 'student_1':[True,True,True,True], 'student_2':[True,True,False,False], 'student_3':[True,False,False,False], 'student_4':[False,False,False,True]})

df = df.set_index('classroom_id')

我只是不太知道如何查询我想要的,也就是问,例如:

How many times is student_1 and student_2 the ONLY true values?

或者

How many times is student_1 and student_2 the ONLY students in a classroom?

预期结果:

1 (classroom 2)

但是,我不想让它回来:

2 (classroom 1 and classroom 2)

我只是不知道该怎么问熊猫。。。 如果有任何问题,特别是我没有说清楚的事情,请告诉我


Tags: andthe数据idfalsetruedfis
2条回答

试试这个

df =pd.DataFrame({'classroom_id':[1,2,3,4], 'student_1':[True,True,True,True], 'student_2':[True,True,False,False], 'student_3':[True,False,False,False], 'student_4':[False,False,False,True]})
df = df.set_index('classroom_id')

group_of_students = ["student_1","student_2"]    # list the students you want to group together

cond1 = df[group_of_students].all(axis=1)    # check for classrooms where these students all have True
cond2 = ~df.drop(group_of_students, axis=1).any(axis=1)    # check for classrooms where all other students have False
df[cond1 & cond2]    # filter df based on cond1 AND cond2

您可以尝试使用布尔索引:

df[df['student_1'] & df['student_2'] & (df.sum(1) == 2)]

输出:

              student_1  student_2  student_3  student_4
classroom_id                                            
2                  True       True      False      False

而且,要获得计数,可以使用shape

df[df['student_1'] & df['student_2'] & (df.sum(1) == 2)].shape[0]

输出:

1

相关问题 更多 >