如何从多个数组和列表创建结构化DataDrame ?



我使用Python3。我有三个列表,一个包含产品分销商的名称,另一个包含产品列表,另一个包含产品分类,最后,我有两个数组。

每个经销商提供15种产品,全部。

distributors = ['d1', 'd2', 'd3', 'd4', 'd5']
products = ['apple', 'carrot', 'potato', 'avocado', 'pumkie', 'banana', 'kiwi', 'lettuce', 'tomato', 'pees', 'pear', 'berries', 'strawberries', 'blueberries', 'boxes']
tips = ['fruit', 'vegetables', 'random']
actual_prix = np.random.rand(15, 5)
prix_prox_year = np.random.rand(15,5)

数组的结构如下:行是按顺序排列的乘积,列是按顺序排列的分配器。我需要的输出如下:

Products  Distributor   Actual      Next_year    Type
0  apple         d1      0.16147847    0.28173206   fruit
1    ...        ...        ...          ...         fruit
2  apple         d5        ...          ...         fruit
...   ...        ...        ...          ...          ...
15  boxes         d5        ...          ...         random

这只是一个例子,因为我的数组大小是(1010, 33)

任何想法?

您可以使用来自itertools的product来创建所有的交互,排序对于获得数据的模式非常重要。对于数组,您需要平铺,以便在tips中重复每个元素,并将其分解为单个长数组,以便长度匹配。

我将你的一个数组更改为递增计数,这样就可以很明显地看到发生了什么。

示例数据
import numpy as np
distributors = ['d1', 'd2', 'd3', 'd4', 'd5']
products = ['apple', 'carrot', 'potato', 'avocado', 'pumkie', 'banana', 
'kiwi', 'lettuce', 'tomato', 'pees', 'pear', 'berries', 'strawberries', 
'blueberries', 'boxes']
tips = ['fruit', 'vegetables', 'random']
actual_prix = np.arange(15*5).reshape(15,5)
prix_prox_year = np.random.rand(15,5)

from itertools import product
import pandas as pd

df = (pd.DataFrame([*product(products, tips, distributors)],
columns=['Products', 'Type', 'Distributor'])
.assign(Actual = np.tile(actual_prix, len(tips)).ravel(),
Next_year = np.tile(prix_prox_year, len(tips)).ravel()))

print(df)
Products        Type Distributor  Actual  Next_year
0      apple       fruit          d1       0   0.391903
1      apple       fruit          d2       1   0.378865
2      apple       fruit          d3       2   0.056134
3      apple       fruit          d4       3   0.623146
4      apple       fruit          d5       4   0.879184
5      apple  vegetables          d1       0   0.391903
6      apple  vegetables          d2       1   0.378865
...
219    boxes  vegetables          d5      74   0.804884
220    boxes      random          d1      70   0.900764
221    boxes      random          d2      71   0.455267
222    boxes      random          d3      72   0.489814
223    boxes      random          d4      73   0.054597
224    boxes      random          d5      74   0.804884

您可以使用itertools和set函数来获得唯一的组合,然后将其放入数据框架中。

import itertools
store = ["a", "b", "c"]
prods = ['apple', 'banana']
all_combinations = [list(zip(each_permutation, prods)) for each_permutation in itertools.permutations(store, len(prods))]

最新更新