defmy_crosstab(s1, s2, dropna=True):
idx1 =(s1.cat.categories if s1.dtype.name =='category'andnot dropna else s1.unique())# 确定当前的s1中全部的属性
idx2 =(s2.cat.categories if s2.dtype.name =='category'andnot dropna else s2.unique())#确定s2
res = pd.DataFrame(np.zeros((idx1.shape[0], idx2.shape[0])), index=idx1, columns=idx2)#构建数组for i, j inzip(s1, s2):
res.at[i, j]+=1
res = res.rename_axis(index=s1.name, columns=s2.name).astype('int')return res
df = pd.DataFrame({'A':['a','b','c','a'],'B':['cat','cat','dog','cat']})
df.B = df.B.astype('category').cat.add_categories('sheep')
my_crosstab(df.A, df.B)
my_crosstab(df.A, df.B, dropna=False)
B
cat
dog
sheep
A
a
2
0
0
b
1
0
0
c
0
1
0
Ex2:钻石数据集
data =[[0.13,'Fair','I1',326],[0.31,'Premium','SI2',326],[0.13,'Good','VS1',327],[0.23,'Ideal','SI2',326],[0.25,'Premium','VS2',326],[0.27,'Good','VS1',327],[0.28,'Ideal','SI2',326],[0.20,'Premium','SI1',326],[0.21,'Good','VVS1',327],[0.24,'Ideal','SI2',326],[0.26,'Premium','SI1',326],[0.24,'Very Good','VVS2',327],[0.23,'Ideal','SI2',326],[0.21,'Premium','SI1',326],[0.23,'Ideal','IF',327]]
74.5 µs ± 4.3 µs per loop (mean ± std. dev. of 7 runs, 30 loops each)
The slowest run took 4.54 times longer than the fastest. This could mean that an intermediate result is being cached.
551 µs ± 337 µs per loop (mean ± std. dev. of 7 runs, 30 loops each)
Ex1:统计未出现的类别import numpy as npimport pandas as pddf = pd.DataFrame({'A':['a','b','c','a'], 'B':['cat','cat','dog','cat']})pd.crosstab(df.A, df.B) B cat dog A a 2