从多个列表创建有序数据框

时间:2019-02-28 20:23:33

标签: python pandas dataframe

我想基于多个列表创建一个有序的熊猫数据框。

这是我的3个列表:

Month=['Jan','Feb','March']
Type=['Aluminium','Copper','Gold']
Model=['Car','Truck']

我想创建一个数据框,以使每个实例都包含 Month Type Model

这是我需要的输出数据框:

    Month     Type           Model
0   Jan        Aluminium     Car
1   Feb        Aluminium     Car
2   March      Aluminium     Car
3   Jan        Aluminium     Truck
4   Feb        Aluminium     Truck
5   March      Aluminium     Truck
6   Jan        Copper        Car
7   Feb        Copper        Car
8   March      Copper        Car
9   Jan        Copper        Truck
10  Feb        Copper        Truck
11  March      Copper        Truck
12  Jan        Gold          Car
13  Feb        Gold          Car
14  March      Gold          Car
15  Jan        Gold          Truck
16  Feb        Gold          Truck
17  March      Gold          Truck

1 个答案:

答案 0 :(得分:1)

一种简单的方法MultiIndex

s=pd.MultiIndex.from_product([Model,Type,Month]).to_frame().reset_index(drop=True)
s    
Out[98]: 
        0          1      2
0     Car  Aluminium    Jan
1     Car  Aluminium    Feb
2     Car  Aluminium  March
3     Car     Copper    Jan
4     Car     Copper    Feb
5     Car     Copper  March
6     Car       Gold    Jan
7     Car       Gold    Feb
8     Car       Gold  March
9   Truck  Aluminium    Jan
10  Truck  Aluminium    Feb
11  Truck  Aluminium  March
12  Truck     Copper    Jan
13  Truck     Copper    Feb
14  Truck     Copper  March
15  Truck       Gold    Jan
16  Truck       Gold    Feb
17  Truck       Gold  March