繁体   English   中英

如何使用索引和python中的值制作矩阵?

[英]How to make a matrix using index and the value in python?

我有一个数据集,它有两列:

index  Value 

0      True

1      True

2      False

3      True

是否有可能获得一个看起来像的矩阵

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

我试过pd.crosstab ,仍然无法获得矩阵,有人可以帮忙吗?

一种可能的方式:

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

首先,使用to_numpyValue列的值转换为 numpy 数组。 然后通过使用[:,None]创建一个额外的轴并计算按位和运算来利用 numpy 广播:

vals = df['Value'].to_numpy()

res = pd.DataFrame(vals[:,None] & vals, index=df.index)

输出:

>>> 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM