通过计算单元格中的值来计算共现矩阵 [英] Compute co-occurrence matrix by counting values in cells
本文介绍了通过计算单元格中的值来计算共现矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的数据框
I have a dataframe like this
df = pd.DataFrame({'a' : [1,1,0,0], 'b': [0,1,1,0], 'c': [0,0,1,1]})
我想得到
a b c
a 2 1 0
b 1 2 1
c 0 1 2
其中,a,b,c是列名,当另一列中的过滤器为"1"时,我得到的所有列的计数值为"1".足够,当df.a == 1时,我们计算a = 2,b = 1,c = 0等等
where a,b,c are column names, and I get the values counting '1' in all columns when the filter is '1' in another column. For ample, when df.a == 1, we count a = 2, b =1, c = 0 etc
我做了一个循环来解决
matrix = []
for name, values in df.iteritems():
matrix.append(pd.DataFrame( df.groupby(name, as_index=False).apply(lambda x: x[x == 1].count())).values.tolist()[1])
pd.DataFrame(matrix)
但是我认为有一个更简单的解决方案,对吗?
But I think that there is a simpler solution, isn't it?
推荐答案
您似乎想要矩阵乘积,因此请使用 DataFrame.dot
:
You appear to want the matrix product, so leverage DataFrame.dot
:
df.T.dot(df)
a b c
a 2 1 0
b 1 2 1
c 0 1 2
或者,如果您希望在没有熊猫开销的情况下达到相同的性能水平,则可以使用 np.dot
:
v = df.values
pd.DataFrame(v.T.dot(v), index=df.columns, columns=df.columns)
或者,如果您想变得可爱,
Or, if you want to get cute,
(lambda a, c: pd.DataFrame(a.T.dot(a), c, c))(df.values, df.columns)
a b c
a 2 1 0
b 1 2 1
c 0 1 2
这篇关于通过计算单元格中的值来计算共现矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文