将平面记录表转换为Pandas中的聚合数据帧

将平面记录表转换为Pandas中的聚合数据帧,pandas,dataframe,group-by,pivot-table,Pandas,Dataframe,Group By,Pivot Table,我有一个关于物体的平面记录表。对象有一个类型(ObjType)并托管在容器(ContainerId)中。这些记录还有一些关于对象的其他属性。然而,目前对它们不感兴趣。因此,基本上,数据如下所示: Id ObjName XT ObjType ContainerId 2 name1 x1 A 2 3 name2 x5 B 2 22 name5 x3 D 7 25 name6 x2 E 7 35 name7 x3 G 7 .. ..

我有一个关于物体的平面记录表。对象有一个类型(ObjType)并托管在容器(ContainerId)中。这些记录还有一些关于对象的其他属性。然而,目前对它们不感兴趣。因此,基本上,数据如下所示:

Id  ObjName XT  ObjType ContainerId
2   name1   x1  A   2
3   name2   x5  B   2
22  name5   x3  D   7
25  name6   x2  E   7
35  name7   x3  G   7
..
..
92  name23  x2  A   17
95  name24  x8  B   17
99  name25  x5  A   21
我试图做的是“重新透视”这些数据,通过查看它们在聚合中承载的对象类型,进一步分析哪些容器“相似”

因此,我希望将上述数据转换为下表:

ObjType        A    B    C    D    E    F    G
ContainerId                                   
2            2.0  1.0  1.0  0.0  0.0  0.0  0.0
7            0.0  0.0  0.0  1.0  2.0  1.0  1.0
9            1.0  1.0  0.0  1.0  0.0  0.0  0.0
11           0.0  0.0  0.0  2.0  3.0  1.0  1.0
14           1.0  1.0  0.0  1.0  0.0  0.0  0.0
17           1.0  1.0  0.0  0.0  0.0  0.0  0.0
21           1.0  0.0  0.0  0.0  0.0  0.0  0.0
这就是我目前如何做到这一点的(在经历了大量的绊脚石之后,并使用了来自以下问题的各种技巧,例如)。我得到了正确的结果,但是,作为熊猫和蟒蛇的新手,我觉得我必须走很长的路。(我添加了一些注释来解释这些痛点。)


询问:是否有人可以分享其他可能执行此转换的方法?

这是
pd.crosstab
的一个用例

e、 g


的确,我的错。在整个过程中,我使用“groupby”和“dataframe”搜索了很多内容。在我的经历即将结束的时候,我从另一个关于pivot table的博客上得到了这两个片段,我想我没有想到再在软件上搜索“pandas”和“pivot table”。一路上我读了很多其他的东西…但是偶然发现真的很有帮助。写得好!
import pandas as pd
rdf = pd.read_csv('.\\testdata.csv')

#The data in the below group-by is all that is needed but in a re-pivoted format...
rdfg = rdf.groupby('ContainerId').ObjType.value_counts()

#Remove 'ContainerId' and 'ObjType' from the index
#Had to do reset_index in two steps because otherwise there's a conflict with 'ObjType'. 
#That is, just rdfg.reset_index() does not work!
rdx = rdfg.reset_index(level=['ContainerId'])

#Renaming the 'ObjType' column helps get around the conflict so the 2nd reset_index works.
rdx.rename(columns={'ObjType':'Count'}, inplace=True)
cdx = rdx.reset_index()

#After this a simple pivot seems to do it
cdf = cdx.pivot(index='ContainerId', columns='ObjType',values='Count')
#Replacing the NaNs because not all containers have all object types
cdf.fillna(0, inplace=True)
In [539]: pd.crosstab(df.ContainerId, df.ObjType)
Out[539]: 
ObjType      A  B  D  E  G
ContainerId
2            1  1  0  0  0
7            0  0  1  1  1
17           1  1  0  0  0
21           1  0  0  0  0