从 pandas 一列创建布尔矩阵 [英] Creating boolean matrix from one column with pandas

查看:286
本文介绍了从 pandas 一列创建布尔矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一个答案,但我不知道该怎么寻找,所以我会问,而不是在这里。我是一个初学者的Python和熊猫爱好者。

I have been searching for an answer but I don't know what to search for so I'll ask here instead. I'm a beginner python and pandas enthusiast.

我有一个数据集在这里我想从一列产生的矩阵。基质应当具有1的值,如果在列和其转置状态的值等于0,如果它不是。

I have a dataset where i would like to produce a matrix from a column. The matrix should have the value of 1 if the value in the column and its transposed state is equal and 0 if its not.

输入:

  id x1
   A  1
   B  3
   C  1
   D  5

输出:

  A  B  C  D

A 1  0  1  0

B 0  1  0  0

C 1  0  1  0

D 0  0  0  1

我想为六个不同的列做到这一点,并添加所产生的矩阵到一个矩阵,其中的值范围为0-6,而不是仅仅0-1。

I would like to do this for six different columns and add the resulting matrixes into one matrix where the values range from 0-6 instead of just 0-1.

推荐答案

部分原因是由于还没有方便的笛卡儿连接(哨子,看着远处的),我倾向于下降到numpy的水平,利用广播,当我需要做这样的事情。 IOW,因为我们可以做这样的事情。

Partly because there's as of yet no convenient cartesian join (whistles and looks away), I tend to drop down to numpy level and use broadcasting when I need to do things like this. IOW, because we can do things like this

>>> df.x1.values - df.x1.values[:,None]
array([[ 0,  2,  0,  4],
       [-2,  0, -2,  2],
       [ 0,  2,  0,  4],
       [-4, -2, -4,  0]])

我们可以做

>>> pdf = pd.DataFrame(index=df.id.values, columns=df.id.values, 
                       data=(df.x1.values == df.x1.values[:,None]).astype(int))
>>> pdf
   A  B  C  D
A  1  0  1  0
B  0  1  0  0
C  1  0  1  0
D  0  0  0  1

这篇关于从 pandas 一列创建布尔矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆