[英]How to make a matrix using index and the value in python?
I have a dataset, which has two columns:我有一个数据集,它有两列:
index Value
0 True
1 True
2 False
3 True
Is it possible to obtain a matrix that looks like是否有可能获得一个看起来像的矩阵
index 0 1 2 3
0 True True False True
1 True True False True
2 False False False False
3 True True False True
I tried pd.crosstab
, still not able to get the matrix, can anyone please help?我试过
pd.crosstab
,仍然无法获得矩阵,有人可以帮忙吗?
A possible way:一种可能的方式:
m = np.tile(df['Value'], len(df)).reshape(-1, len(df)) * df[['Value']].values
out = pd.DataFrame(m)
print(out)
# Output
0 1 2 3
0 True True False True
1 True True False True
2 False False False False
3 True True False True
First, convert the values of Value
columns to a numpy array using to_numpy
.首先,使用
to_numpy
将Value
列的值转换为 numpy 数组。 Then take advantage of numpy broadcasting by creating an extra axis with [:,None]
and computing the bitwise and operation:然后通过使用
[:,None]
创建一个额外的轴并计算按位和运算来利用 numpy 广播:
vals = df['Value'].to_numpy()
res = pd.DataFrame(vals[:,None] & vals, index=df.index)
Output:输出:
>>> res
0 1 2 3
index
0 True True False True
1 True True False True
2 False False False False
3 True True False True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.