[英]Creating list of list using Python
Having a data frame as below:need to convert to list of list as below:具有如下数据框:需要转换为列表列表如下:
product1产品1 | product2产品2 | time时间 |
---|---|---|
Apple苹果 | Apple苹果 | 0 0 |
Apple苹果 | Mango芒果 | 20 20 |
Apple苹果 | Orange橙子 | 24 24 |
Mango芒果 | Apple苹果 | 30 30 |
Mango芒果 | Mango芒果 | 0 0 |
Mango芒果 | Orange橙子 | 24 24 |
orange橙 | Apple苹果 | 12 12 |
orange橙 | orange橙 | 0 0 |
orange橙 | mango芒果 | 24 24 |
Need to create a matrix whose logic is like this:需要创建一个逻辑如下的矩阵:
The output needs to be a list of list of format as below: output 需要是格式列表如下:
[[0,24,20],[12,0,24],[30,24,0]]
I tried the below code:我尝试了以下代码:
df.groupby(['product1','product2'])['time'].apply(list) df.groupby(['product1','product2'])['time'].apply(list)
From the looks of this, this is known as a pivot table.从这个看起来,这被称为 pivot 表。 You can create it by using pandas.pivot_table method.您可以使用pandas.pivot_table方法创建它。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.