简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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