Home > OS >  Creating list of list using Python
Creating list of list using Python

Time:08-16

Having a data frame as below:need to convert to list of list as below:

product1 product2 time
Apple Apple 0
Apple Mango 20
Apple Orange 24
Mango Apple 30
Mango Mango 0
Mango Orange 24
orange Apple 12
orange orange 0
orange mango 24

Need to create a matrix whose logic is like this:

img

The output needs to be a list of list of format as below:

[[0,24,20],[12,0,24],[30,24,0]]

I tried the below code:

df.groupby(['product1','product2'])['time'].apply(list)

CodePudding user response:

From the looks of this, this is known as a pivot table. You can create it by using pandas.pivot_table method.

To create the above matrix, you need to write this code.

pt = data.pivot_table(index="product1", columns="product2", values="time")

To get this in list of list form. Store this in a variable and use this.

pt.values.tolist()
  • Related