Home > Blockchain >  How to make a matrix using index and the value in python?
How to make a matrix using index and the value in python?

Time:06-27

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?

CodePudding user response:

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

CodePudding user response:

First, convert the values of Value columns to a numpy array using to_numpy. Then take advantage of numpy broadcasting by creating an extra axis with [:,None] and computing the bitwise and operation:

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
  • Related