单元格中具有多个值的表的计数/透视

2024-06-16 13:18:06 发布

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

我有一些数据如下所示:

Class                    Instructor
Intro to Philosophy      Jake
Algorithms               Ashley/Jake
Spanish I                Ashley
Vector Calculus          Jake
Intro to Philosophy      Jake

我怎样才能得到一个计数或支点,如下图所示,其中Ashley和Jake都教授一门课的实例被正确地添加到计数中?一个讲师的例子是微不足道的,但同一个单元中的一个班级有两个或两个以上的讲师却让我大吃一惊

我想谈谈这样的事情:

                         Jake        Ashley
Intro to Philosophy         2             0
Algorithms                  1             1
Spanish I                   0             1
Vector Calculus             1             0
Total                       4             2

Tags: to数据class计数vectoralgorithmsintrospanish
3条回答

您可以这样做:

In [1746]: df.Instructor = df.Instructor.str.split('/')

In [1747]: df = df.explode('Instructor')

In [1751]: x = df.groupby('Instructor').Class.value_counts().reset_index(level=0).pivot(columns='Instructor', values='Class').fillna(0)

In [1754]: x.loc['Total'] = x.sum()

In [1755]: x
Out[1755]: 
Instructor           Ashley  Jake
Class                            
Algorithms              1.0   1.0
Intro_to_Philosophy     0.0   2.0
Spanish_I               1.0   0.0
Vector_Calculus         0.0   1.0
Total                   2.0   4.0

您可以使用.str.get_dummies拆分Instructor字段并对其进行二值化。然后您可以按Class分组:

ret = (df['Instructor'].str.get_dummies('/')
     .groupby(df['Class']).sum()
)
ret.loc['Total'] = ret.sum()

输出:

                     Ashley  Jake
Class                            
Algorithms                1     1
Intro to Philosophy       0     2
Spanish I                 1     0
Vector Calculus           0     1
Total                     2     4

让我们在explode之后做crosstab

df.Instructor = df.Instructor.str.split('/')

df = df.explode('Instructor')

out = pd.crosstab(df['Class'], df['Instructor'])

相关问题 更多 >