从Series列表创建DataFrame

时间:2018-02-19 15:21:45

标签: python python-3.x pandas dataframe

我有下面的系列列表:

import pandas as pd
my_series_a = pd.Series([1,2,2,4,5], name='Group_A')
my_series_b = pd.Series([50,50,70], name='Group_B')
my_series_c = pd.Series([333,222,111,111], name='Group_C')
my_list = [my_series_a, my_series_b, my_series_c]

我需要创建一个包含2列[Group,Sub-Group]的数据框:

组:系列名称
子组:每个系列的唯一值

结果应该是:

Group     Sub-Group
Group_A    1
Group_A    2
Group_A    4
Group_A    5
Group_B    50
Group_B    70
Group_C    333
Group_C    222
Group_C    111

1 个答案:

答案 0 :(得分:2)

使用列表推导和pd.unique()功能:

In [11]: pd.DataFrame([(arr.name, i) for arr in my_list for i in pd.unique(arr)],
                      columns=['Group', 'Sub-Group'])
Out[11]: 
     Group  Sub-Group
0  Group_A          1
1  Group_A          2
2  Group_A          4
3  Group_A          5
4  Group_B         50
5  Group_B         70
6  Group_C        333
7  Group_C        222
8  Group_C        111